Tree: Height of a Binary Tree

Sort by

recency

|

973 Discussions

|

  • + 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;
    }
    
  • + 0 comments
    def height(root):
        if root is None:
            return -1
        return max(height(root.left), height(root.right)) + 1
    
  • + 0 comments

    Posting my java solution since I think it's quite simple to understand.

    public static int height(Node root) {
            if (root==null || (root.left==null && root.right==null))
               return 0;
            
            int heightLeft=0;
            int heightRight=0;
            
            if(root.left!=null){
                heightLeft=height(root.left)+1;
            }        
            if(root.right!=null){
                heightRight=height(root.right)+1;
            }
            
            return Math.max(heightLeft, heightRight);        
        }
    
  • + 1 comment

    You muppets. The javascript implementation contains all nodes in the right. Creating a right skewed tree.

    e.g.

    {
        "data": 3,
        "left": null,
        "right": {
            "data": null,
            "left": null,
            "right": {
                "data": null,
                "left": null,
                "right": {
                    "data": null,
                    "left": null,
                    "right": {
                        "data": null,
                        "left": null,
                        "right": null
                    }
                }
            }
        }
    }