[Help] why my solution is wrong?


  • 0
    public class BalancedBinaryTree {
    
        boolean balance = true;
    
        public boolean isBalanced(TreeNode root) {
            if (root == null)
                return true;
            return (Math.abs(depth(root.left) - depth(root.right)) <= 1) && balance;
        }
    
        public int depth(TreeNode root) {
            if (balance) {
                if (root == null)
                    return 0;
    
                int lengthOfLeft = depth(root.left);
                int lengthOfRight = depth(root.right);
    
                if (Math.abs(lengthOfLeft - lengthOfRight) > 1) {
                    balance = false;
                }
                return Math.max(lengthOfLeft, lengthOfRight) + 1;
            } else {
                return 0;
            }
        }
    
    

Log in to reply
 

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