平衡树,即平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
public boolean IsBalanced_Solution(TreeNode root) {
//若结点为空,是平衡二叉树
if(root==null)
return true;
//若结点不为空,判断它的左右子树是否高度差绝对值小于等于1
else{
//若左右子树的高度差绝对值小于等于1,判断左右子树是不是平衡二叉树
if(Math.abs(height(root.left)-height(root.right))<=1)
return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
else
return false;
}
}
//求一个树的高度
private int height(TreeNode root){
if(root==null)
return 0;
else{
int hL=height(root.left);
int hR=height(root.right);
return hL>hR?hL+1:hR+1;
}
}
京公网安备 11010502036488号