剑指 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);
        //如果左右子树的深度差值大于1, 说明不是平衡树,返回false
        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;
    }
}

 

posted @ 2020-12-17 15:00  peanut_zh  阅读(57)  评论(0编辑  收藏  举报