剑指 Offer 55 - II. 平衡二叉树

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 //从底向上,避免大量重复计算
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;

        int nleft = treeDepth(root.left);
        int nright =treeDepth(root.right);
        if(Math.abs(nleft - nright) >1)
            return false;

        return isBalanced(root.left) && isBalanced(root.right);
    }
    int treeDepth(TreeNode root){
        if(root == null) 
            return 0;
        return Math.max(treeDepth(root.left),treeDepth(root.right))+1;
    }
}

 

上一篇:55


下一篇:喜迎双旦 岁末狂欢丨誉天2021开年大促