110. Balanced Binary Tree

class Solution {
    boolean result = true;
    public boolean isBalanced(TreeNode root) {
        // concept: height: from bottom to top
        postOrder(root);
        return result;
    }
    
    private int postOrder(TreeNode node){
        // as long as result is false, no need to trasverse the rest of the tree;
        if (node==null || !result) return 0;
        
        int leftHeight = postOrder(node.left);
        int rightHeight = postOrder(node.right);
        if (Math.abs(leftHeight-rightHeight)>1){
            result = false;
        }
        return Math.max(leftHeight, rightHeight)+1;
    }
}

Last updated

Was this helpful?