Tree: Height of a Binary Tree

  • + 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);        
        }