剑指 Offer 55

/**
 * 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;
    }
}
原文地址:https://www.cnblogs.com/peanut-zh/p/14149679.html