A simple Java code


  • 0
    L
     public boolean isBalanced(TreeNode root) {
            return helper(root).balanced;
        }
        
        private Balancer helper(TreeNode root) {
            if(root==null) {
                return new Balancer(true,0);
            }
            
            Balancer left =  helper(root.left);
            Balancer right = helper(root.right);
            
            if(!left.balanced || !right.balanced || !(Math.abs(left.height-right.height) <=1)) {
                return new Balancer(false,0);
            }
            
            return new Balancer(true,1+Math.max(left.height,right.height));
        }
        
        private class Balancer {
            private boolean balanced;
            private int height;
            Balancer(boolean balanced,int height) {
                this.balanced = balanced;
                this.height = height;
            }
        }
    

Log in to reply
 

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