Java 1ms optimized


  • 0
    P

    I found most java solutions find leftHeight and rightHeight and then compare them with -1.
    But you can avoid traversing any of left or right side by checking for -1 before.

    public int getHeight(TreeNode root) 
        {
            if(root == null) 
            {
                return 0;
            }
            int leftHeight = getHeight(root.left);
            if(leftHeight == -1)
            {
                return -1;
            }
            int rightHeight = getHeight(root.right);
            if(rightHeight == -1)
            {
                return -1;
            }
            if(Math.abs(leftHeight - rightHeight) > 1)
            return -1;
            else
            return (Math.max(leftHeight, rightHeight)) + 1;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.