Tree: Height of a Binary Tree

Sort by

recency

|

976 Discussions

|

  • + 0 comments

    My Java solution w/ linear time and o(h) space:

    public static int height(Node root) {
            if(root == null) return -1; //no height
            
            int leftHeight = height(root.left);
            int rightHeight = height(root.right);
            
            return 1 + Math.max(leftHeight, rightHeight);
        }
    
  • + 0 comments

    Do we need to build a tree root from stdin ourself? Just created my function in editor as described in thr problem, my func is not called and no output.

  • + 1 comment

    For anyone having issues with the broken Javascript boilerplate code, you can overwrite the solution function to fix it, you can add this to your code:

    var solution = () =>  {
        const tree = new Tree();
    
        _stdin_array[1]
            .split(" ")
            .map(x => parseInt(x))
            .forEach(value => {
                tree.root = tree.insert(tree.root, value);
            })
    
        const height = treeHeight(tree.root);
        process.stdout.write(`${height}`);
    }
    
    • + 0 comments

      Thank you!

  • + 0 comments

    python

    def height(root):
        if root is None:
            return -1
        h_left=height(root.left)
        h_right=height(root.right)
        
        return max(h_left,h_right) +1
    
  • + 0 comments
    int height(Node* root) {
        // Write your code here.
        if (!root) return -1;
        int left = height(root->left);
        int right = height(root->right);
        return max(left, right) + 1;
    }