題目描述
輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。
分析:平衡二叉樹的左右子樹都是平衡二叉樹,平衡二叉樹的左右子樹高度差不超過1。最直接的想法就是遞歸調用算出來每一個子樹的高度然後作差去比,但是那樣的話會重複訪問很多次結點,所以不推薦。如果用後序遍歷的話,每個結點只需要遍歷一次就可以。
代碼:
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int Depth=0;
return IsBalanced(pRoot,&Depth);
}
bool IsBalanced(TreeNode* pRoot,int* pDepth){
if(pRoot==NULL){
*pDepth=0;
return true;
}
int left=0,right=0;
if(IsBalanced(pRoot->left,&left) && IsBalanced(pRoot->right,&right)){
int diff=left-right;
if(diff<=1 && diff>=-1){
*pDepth=1+(left>right?left:right);
return true;
}
}
return false;
}
};