Java 1 ms 6 lines


  • 1
    Y

    Here the depth(TreeNode) function will return normal depth if tree is balanced, -1 otherwise.

        public boolean isBalanced(TreeNode root) {
            return depth(root) >= 0;
        }
        
        int depth(TreeNode root) {
            if (root == null) return 0;
            int l, r;
            if ((l = depth(root.left )) < 0) return -1;
            if ((r = depth(root.right)) < 0) return -1;
            if (Math.abs(l - r) > 1) return -1;
            return Math.max(l, r) + 1;
        }
    

Log in to reply
 

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