題目:輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。
首先需要知道什麼是平衡二叉樹。而且之前做過一道題是對稱二叉樹,二者的區別和相似點在什麼地方。
平衡二叉樹:如果某二叉樹的中的任意節點的左右子樹的深度相差不超過1,那麼它就是一個平衡二叉樹。
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot == NULL)
return true;
int left = TreeDepth(pRoot->left);
int right = TreeDepth(pRoot->right);
int dif = left-right;
if(dif<-1 || dif>1){
return false;
}
return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
}
int TreeDepth(TreeNode* pRoot){
if(pRoot == NULL)
return 0;
//int nLeft = TreeDepth(pRoot->left);
//int nRight = TreeDepth(pRoot->right);
//return (nLeft>nRight)?(nLeft+1):(nRight+1);
int nLeft = 1 + TreeDepth(pRoot->left);
int nRight = 1 + TreeDepth(pRoot->right);
return (nLeft>nRight)?nLeft:nRight;
}
};
上述方法一個節點會被重複遍歷多次,時間效率不高。如果採用後續遍歷的方式遍歷二叉樹的每個節點,那麼在遍歷到一個節點之前,我們就已經遍歷了它的左、右子樹。只要在遍歷每個節點的時候記錄它的深度(某一個節點的深度等於它到葉節點的路徑長度),就可以一邊遍歷一邊判斷每個節點是不是平衡的。(劍指offer思路)
class Solution {
public:
bool IsBalanced(TreeNode* pRoot,int & depth) {
if(pRoot == NULL)
return true;
int left=0;
int right=0;
if(IsBalanced(pRoot->left,left) && IsBalanced(pRoot->right,right)){
int diff = left-right;
if(diff<-1 || diff>1)
return false;
depth = 1+(left>right?left:right);
return true;
}
return false;
}
bool IsBalanced_Solution(TreeNode* pRoot){
int depth = 0;
return IsBalanced(pRoot,depth);
}
};