題目描述
輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。
思路:平衡二叉樹要麼爲空樹要麼左右子樹高度差小於等於1,後序遍歷,每遍歷到一個節點的時候我們已經遍歷了該節點的左右子樹,只要在遍歷每個節點的時候記錄他的深度,就可以一邊遍歷一邊判斷該節點是不是平衡的。
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth=0;
return IsBalanced_Solution_Core(pRoot, depth);
}
bool IsBalanced_Solution_Core(TreeNode* pRoot,int &depth)
{
if(!pRoot)
{
depth=0;
return true;
}
int l,r;
if(IsBalanced_Solution_Core(pRoot->left,l)&&IsBalanced_Solution_Core(pRoot->right,r))
{
int diff = l-r;
if(diff>1||diff<-1)
return false;
else
{
depth = (l>r?l:r)+1;
return true;
}
}
return false;
}
};