Java solution in a postorder traversal manner (recursive)


  • 0
    boolean flag=true;
    public boolean isBalanced(TreeNode root) {
        if(root==null) return true;
        balanceHelper(root);
        return flag;
    }
    
    private int balanceHelper(TreeNode root){
        if(root==null) return -1; 
        if(root.left==null && root.right==null ) return 0;
        
        int l=balanceHelper(root.left)+1;
        int r=balanceHelper(root.right)+1;
    
        if(Math.abs(l-r)>1) flag=false;
        
        return Math.max(l,r);
        
    }

Log in to reply
 

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