一、平衡二叉树
对于树中的任何一个节点,它的左子树和右子树的高度差不超过1
那么,这里就有两个方面考虑:
1、怎样求子树的高度
2、如何判断是否平衡?
这里,使用递归来实现
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class Balance {
public boolean isBalance(TreeNode root){
//首先判断root是否为空,为空说明没有子树,是平衡二叉树
if(root==null){
return true;
}
//root不为空,来计算左子树和右子树的高度
int leftHeight=getTreeHeight(root.left);
int rightHeight=getTreeHeight(root.right);
//计算左右子树高度差
int lack=Math.abs(leftHeight-rightHeight);
if(lack>1){
return false;
}
//递归判断
return isBalance(root.left)&&isBalance(root.right);
}
public static int getTreeHeight(TreeNode root){
//求树的高度
if(root==null){
return 0;
}
//一棵树的高度等于它的左子树和右子树高度中的最大值+1
//+1 加上自身这一层
return Math.max(getTreeHeight(root.left),getTreeHeight(root.right))+1;
}
}