假如有一個二叉樹,需要確定它是否是平衡二叉樹。最直接的做法,就是遍歷每個結點,藉助一個獲取樹深度的遞歸函數,根據該結點的左右子樹高度差判斷是否平衡,然後遞歸地對左右子樹進行判斷。
public boolean IsBalance_Solution(TreeNode root){
if(root==null) return true;
int left = depth(root.left);
int right = depth(root.right);
if(Math.abs(left-right)>1){
return false;
}
// return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
return true;
}
public int depth(TreeNode root){
if(root==null){
return 0;
}
int left = depth(root.left);
int right = depth(root.right);
return left>right?(left+1):(right+1);
}
其次是,採用兩次遞歸,判斷根左右子樹是否爲平衡二叉樹:
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null) return true;
if(Math.abs(getHeight(root.left)-getHeight(root.right))>1) return false;
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
public int getHeight(TreeNode root){
if(root==null) return 0;
return max(getHeight(root.left),getHeight(root.right))+1;
}
private int max(int a, int b){
return (a>b)?a:b;
}
但是這種做法很明顯的一個問題就是,再判斷上層結點的時候,會多次重複遍歷下層結點,增加了不必要
的開銷。如果改爲從下往上遍歷,如果子樹是平衡二叉樹,則返回子樹的高度;如果發現子樹不是平
衡二叉樹,則直接停止遍歷,這樣至多隻對每一個結點訪問一次。
public boolean IsBalanced_Solution3(TreeNode root){
return etDepth(root) !=-1;
}
private int etDepth(TreeNode root){
if(root == null) return 0;
int left = etDepth(root.left);
if(left == -1) return -1;
int right = etDepth(root.right);
if(right == -1) return -1;
return Math.abs(left-right) >1 ? -1:1+Math.max(left, right);
}