题目
leetcode 平衡二叉树
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
总结
平衡二叉树:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
方法一:遍历每个结点
遍历每个结点,借助一个获取树深度的递归函数,根据该结点的左右子树高度差判断是否平衡,然后递归地对左右子树进行判断。然而,这种做法有很明显的问题,在判断上层结点的时候,会多次重复遍历下层结点,增加了不必要的开销。见方法二。
class Solution {
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 Math.max(maxDepth (root.left), maxDepth (root.right)) + 1;
}
}
方法二:运用剪枝法减少不必要的开销
改为从下往上遍历,如果子树是平衡二叉树,则返回子树的高度;如果发现子树不是平衡二叉树,则直接停止遍历,这样至多只对每个结点访问一次。
class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
// -1代表不平衡
return getDepth(root) != -1;
}
private int getDepth(TreeNode root) {
if (root == null) return 0;
// 如果发现左子树不平衡则直接返回
int left = getDepth(root.left);
if (left == -1) return -1;
// 如果发现右子树不平衡则直接返回
int right = getDepth(root.right);
if (right == -1) return -1;
return Math.abs(left - right) > 1 ? -1 : 1 + Math.max(left, right);
}
}