輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。
思路一:暴力遞歸,判斷每個兩邊的高度差是否大於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);
}