平衡二叉树 --剑指offer

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。
从上往下计算树的深度 有重复计算
public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null) return true;
        if(Math.abs(getDepth(root.left)-getDepth(root.right)) > 1) return  false;
        return IsBalanced_Solution(root.left) &&  IsBalanced_Solution(root.right);
    }

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

}

从下往上计算 相当后序遍历

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        return getDepth(root) == -1?false:true;
    }

    public int getDepth(TreeNode node){
        if(node == null){
            return 0;
        }
        int left=0,right=0;
        if(node.left != null){
            left=getDepth(node.left);
        }
        if(left == -1) return -1;
        if(node.right != null){
            right=getDepth(node.right);
        }
        if(right == -1) return -1;
        return Math.abs(left-right) >1 ?-1:1+Math.max(left,right);
    }
}
原文地址:https://www.cnblogs.com/nlw-blog/p/12444883.html