题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
平衡二叉树(Balanced Binary Tree)具有以下性质
:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
思路: 递归判断左右子树的高度,比较高度差。
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
int depth=depth(root);
return depth!=-1;
}
public int depth(TreeNode root){
if(root==null)return 0;
int ldepth=depth(root.left);
if(ldepth==-1)return -1;
int rdepth=depth(root.right);
if(rdepth==-1)return -1;
return Math.abs(ldepth-rdepth)>1?-1:Math.max(ldepth,rdepth)+1;
}
}