题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
错误做法,对平衡二叉树的理解出现了偏差,平衡二叉树判断其是否平衡,是判断每个中间节点的左右子树高度差是否小于等于1,而不是对所有叶子节点的位置作比较.
public class Solution {
int max_depth=-1,min_depth=10000;
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null)return true;
isBaleance(root,1);
return max_depth-min_depth<=1;
}
public void isBaleance(TreeNode root,int depth){
if(root.left==null&&root.right==null){
min_depth=Math.min(min_depth,depth);
max_depth=Math.max(max_depth,depth);
return;
}
isBaleance(root.left,depth+1);
isBaleance(root.right,depth+1);
return;
}
}
理解平衡二叉树后,可通过递归遍历整棵树的方式判断是否平衡.
问题:这种做法有很明显的问题,在判断上层结点的时候,会多次重复遍历下层结点,增加了不必要的开销。
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null)return true;
return Math.abs(getDepth(root.left)-getDepth(root.right))<=1&&
IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
}
public int getDepth(TreeNode root){
if(root==null)return 0;
return Math.max(getDepth(root.left),getDepth(root.right))+1;
}
}
改进:如果改为从下往上遍历,如果子树是平衡二叉树,则返回子树的高度;如果发现子树不是平衡二叉树,则直接停止遍历,这样至多只对每个结点访问一次。
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
return getDepth(root)!=-1;
}
public 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);
}
}