DFS:Bottom-up:1ms:Java


  • 0
    K
    public class Solution {
        public boolean isBalanced(TreeNode root) {
            if(root == null) return true;
            if(isBalancedHeight(root) == -1) return false;
            else return true;
        }
        
        private int isBalancedHeight(TreeNode root) {
            if(root == null) return 0;
            int leftHeight = isBalancedHeight(root.left);
            int rightHeight = isBalancedHeight(root.right);
            if(leftHeight == -1 || rightHeight == -1) return -1;
            if((Math.abs(leftHeight-rightHeight)) > 1) return -1;
            return 1+Math.max(leftHeight, rightHeight);
        }
    }
    

Log in to reply
 

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