【问题标题】:Finding the height of a binary tree recursively or iteratively?递归或迭代查找二叉树的高度?
【发布时间】:2019-05-18 23:30:24
【问题描述】:

谁能检查下面的高度代码是否正确?我不确定是否可以使用递归,因为public int height() 没有传入任何参数。我假设空树的高度为 0。

public class BinaryTree {
    private class Node {
        String value;
        Node left;
        Node right
    }

    Node root;

    // Assume there is a constructor and various methods here

    public int height() {
        if (Node == null) {
            return 0;
        }

        return 1 + math.max(left.height(), right.height());
    }
}

【问题讨论】:

    标签: java recursion binary iteration binary-tree


    【解决方案1】:

    这样就可以了。一些代码块移到了合适的位置,递归步骤中的空检查被重写,添加了一个小示例:

    public class BinaryTree {
    
    public static void main(String[] args) {
        Node sports = new Node();
    
        Node individual = new Node();
        Node team = new Node();
        sports.left = individual;
        sports.right = team;
    
        Node javelin = new Node();
        individual.left = javelin;
    
        System.out.println(sports.height()); // Return 3
    }
    
    private static class Node {
    
        Node left;
        Node right;
    
        public int height() {
            return 1 + Math.max(left == null ? 0 : left.height(), right == null ? 0 : right.height());
        }
    
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-10
      • 2018-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-11
      相关资源
      最近更新 更多