平衡二叉树左右子树高度差不超过 1。
分别计算左右子树的高度,若是差值不超过1,则为平衡二叉树。这是最直接的做法,遍历每个结点,借助一个获取树深度的递归函数,根据该结点的左右子树高度差判断是否平衡,然后递归地对左右子树进行判断。
public classSolution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null) {
return true;
}
return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 &&
IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
private int maxDepth(TreeNode root) {
if(root == null) {
return 0;
}
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
这种做法有很明显的问题,在判断上层结点的时候,会多次重复遍历下层结点,增加了不必要的开销。如果改为从下往上遍历,如果子树是平衡二叉树,则返回子树的高度;如果发现子树不是平衡二叉树,则直接停止遍历,这样至多只对每个结点访问一次。
用后序遍历的方法遍历二叉树,则是先遍历了左、右子树,遍历每个节点的时候记录深度,就可以判断每个节点是不是平衡的。
public class Solution {
private boolean isBalanced=true;
public boolean IsBalanced_Solution(TreeNode root) {
height(root);
return isBalanced;
}
private int height(TreeNode root){
if(root==null||!isBalanced){
return 0;
}
int left = height(root.left);
int right=height(root.right);
if(Math.abs(left-right)>1)
isBalanced=false;
return 1+Math.max(left,right);
}
}