输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路一:暴力递归,判断每个两边的高度差是否大于1,但是会有很多多余的计算
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null)
return true;
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
if((left-right>1)||(left-right<-1))
return false;
return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
}
//算树的深度
public int TreeDepth(TreeNode root){
if(root==null)
return 0;
int nleft = TreeDepth(root.left);
int nright = TreeDepth(root.right);
return (nleft>nright)?(nleft+1):(nright+1);
}
思路二:采用从下往上算,当有节点的左右子节点差大于1,就返回-1.这样就不用有多余的计算了。
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null)
return true;
return getDepth(root)!=-1;
}
//从下往上算,当发现左右子树的差大于1的时候,返回-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);
}