Balanced Binary Tree

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: True if this Binary tree is Balanced, or false.
     */
     
    boolean balanced = true;
    
    private int check(TreeNode p) { // return height of subtree rooted at p
        if (p == null) {
            return 0;
        }
        
        int l = check(p.left);
        int r = check(p.right);
        if (Math.abs(l - r) > 1) { // unbalanced
            balanced = false;
        }
        
        return Math.max(l, r) + 1;
    }
    
    public boolean isBalanced(TreeNode root) {
        check(root);
        return balanced;
    }
}

最后更新于

这有帮助吗?