判断平衡二叉树

问题:输入一棵二叉树,判断该二叉树是否是平衡二叉树。

首先,什么是平衡二叉树:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

先求出左右两个子树的深度,若他们的深度差的绝对值>1,则不是平衡二叉树,还有一点最重要的是性质中说了左右两个子树都是一棵平衡二叉树,所以还要判断

IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right)

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
           if(root==null){
                return true;
            }
            if(Math.abs(TreeDepath(root.left)-TreeDepath(root.right))>1)
            return false;
            return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);

        }
       //求二叉树的深度
        public int TreeDepath(TreeNode pRoot){
            if(pRoot==null)
                return 0;
            if(TreeDepath(pRoot.left)>=TreeDepath(pRoot.right)){
                return 1+TreeDepath(pRoot.left);
            }else{
                return 1+TreeDepath(pRoot.right);
            }
        }
}
原文地址:https://www.cnblogs.com/greatluoluo/p/6623373.html