SBS(2)-- 平衡二叉樹判斷演算法(後續遍歷)
阿新 • • 發佈:2019-01-02
目錄
題目
輸入一棵二叉樹的根節點,判斷該樹是不是平衡二叉樹。如果二叉樹中任意節點的左右子樹的深度相差不超過1,那麼他就是平衡二叉樹。
遞迴版本解法
bool IsBalanced(BinaryTreeNode* pRoot)
{
if (pRoot == NULL)
return true;
int left = TreePath(pRoot->m_pLeft);
int right = TreePath(pRoot->m_pRight);
int diff = right - left;
if (diff > 1 || diff < -1)
return false;
return IsBalanced(pRoot->m_pLeft) && IsBalanced(pRoot->m_pRight);
}
上述程式碼簡潔,但是由於一個節點會被重複遍歷多次,時間效率不高。
後續遍歷版本
bool IsBalanced(BinaryTreeNode* pRoot, int* pDepth)
{
if(pRoot == NULL)
{
*pDepth = 0;
return true ;
}
int left, right;
if(IsBalanced(pRoot->m_pLeft, &left) && IsBalanced(pRoot->m_pRight, &right)
{
int diff = left - right;
if(diff <= 1 && diff >= -1)
{
*pDepth = 1 + (left > right ? left : right);
return true ;
}
}
return false;
}
上述程式碼中, 我們用後續遍歷整棵二叉樹。在遍歷某節點的左右子節點之後, 我們可以根據他的左右子節點的深度判斷他是不是平衡的,並得到當前節點的深度。當遍歷到樹的根節點的時候,也就判斷了整顆二叉樹是不是平衡二叉樹。