題目:輸入一棵二叉樹的根結點,推斷該樹是不是平衡二叉樹。
某二叉樹中随意結點的左右子樹的深度相差不超過1。那麼它就是一棵二叉樹。
我們非常easy就能想到一個代碼簡潔卻性能不佳的思路:在周遊樹的每一個結點的時候,調用函數TreeDpth得到它的左右子樹的深度。
假設每一個結點的左右子樹的深度相差都不超過1。依照定義它就是一棵平衡的二又樹。
較好的思路是:用後序周遊的方式周遊整棵二叉樹。
在周遊某結點的左右子結點之後,我們能夠依據它的左右子結點的深度推斷它是不是平衡的,并得到目前結點的深度。
struct BinaryTreeNode{
int m_nValue;
BinaryTreeNode *m_pLeft;
BinaryTreeNode *m_pRight;
};
bool IsBalanced(BinaryTreeNode *pRoot, int *depth)
{
if (pRoot==NULL)
{
*depth=0;
return true;
}
//中間變量,記錄左右子樹的深度
int left,right;
if (IsBalanced(pRoot->m_pLeft,&left)&&IsBalanced(pRoot->m_pRight,&right))
{
//深度差
int Dif=left-right;
if (Dif<=1&&Dif>=-1)
{
*depth=1+(left>right?left:right);
return true;
}
}
return false;
}
//推斷是否是平衡二叉樹
bool IsBalanced(BinaryTreeNode *pRoot)
{
int depth=0;
return IsBalanced(pRoot,&depth);
}