題目:
輸入一課二叉樹的根結點,判斷該樹是不是平衡二叉樹。如果二叉樹中任意結點的左右子樹的深度相差不超過1,那么它就是一棵平衡二叉樹。
思路:
1、重復遍歷結點
參考上一題求二叉樹的深度,先求出根結點的左右子樹的深度,然后判斷它們的深度相差不超過1,如果否,則不是一棵二叉樹;如果是,再用同樣的方法分別判斷左子樹和右子樹是否為平衡二叉樹,如果都是,則這就是一棵平衡二叉樹。
但上面的方法在判斷子樹是否為平衡二叉樹時,會重復遍歷樹的結點,不斷地求子樹的深度,所以效率不高。
2、遍歷一遍結點
我們在遍歷結點的同時記錄下該結點的深度,這樣就可以避免了重復訪問。
代碼:
方法1:
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
};
int TreeDepth(TreeNode* pRoot){
if(pRoot==NULL)
return 0;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
return left>right?(left+1):(right+1);
}
bool IsBalanced(TreeNode* pRoot){
if(pRoot==NULL)
return true;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
int diff=left-right;
if(diff>1 || diff<-1)
return false;
return IsBalanced(pRoot->left) && IsBalanced(pRoot->right);
}
方法2:
bool IsBalanced_1(TreeNode* pRoot,int& depth){
if(pRoot==NULL){
depth=0;
return true;
}
int left,right;
int diff;
if(IsBalanced_1(pRoot->left,left) && IsBalanced_1(pRoot->right,right)){
diff=left-right;
if(diff<=1 || diff>=-1){
depth=left>right?left+1:right+1;
return true;
}
}
return false;
}
bool IsBalancedTree(TreeNode* pRoot){
int depth=0;
return IsBalanced_1(pRoot,depth);
}
在線測試OJ:
http://www.nowcoder.com/books/coding-interviews/8b3b95850edb4115918ecebdf1b4d222?rp=2
AC代碼:
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot==NULL)
return true;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
int diff=left-right;
if(diff>1 || diff<-1)
return false;
return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
}
int TreeDepth(TreeNode* pRoot){
if(pRoot==NULL)
return 0;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
return left>right?(left+1):(right+1);
}
};
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth=0;
return IsBalanced(pRoot,depth);
}
bool IsBalanced(TreeNode* pRoot,int& depth){
if(pRoot==NULL){
depth=0;
return true;
}
int left,right,diff;
if(IsBalanced(pRoot->left,left) && IsBalanced(pRoot->right,right)){
diff=left-right;
if(diff<=1 && diff>=-1){
depth=left>right?left+1:right+1;
return true;
}
}
return false;
}
};
