您的位置:首页 > 职场人生

面试题39:二叉树的深度、判断二叉树是不是平衡

2016-07-18 16:33 585 查看
题目一:

int TreeDepth(BinaryTreeNode* pRoot)
{
if(pRoot == NULL)
return 0;

int nLeft = TreeDepth(pRoot->m_pLeft);
int nRight = TreeDepth(pRoot->m_pRight);

return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}


题目二:判断二叉树是不是平衡

法一:利用TreeDepth判断



bool IsBalanced(BinaryTreeNode* pRoot)
{
if(pRoot== NULL)
return true;

int nLeftDepth = TreeDepth(pRoot->m_pLeft);
int nRightDepth = TreeDepth(pRoot->m_pRight);
int diff = nRightDepth-nLeftDepth;

if (diff>1 || diff<-1)
return false;

return IsBalanced(pRoot->m_pLeft)&&IsBalanced(pRoot->m_pRight);
}


上面的代码固然简洁,但我们也要注意到由于一个节点会被重复遍历多次,这种思路的时间效率不高。例如在函数IsBalance中输入上图中的二叉树,首先判断根结点(值为1的结点)的左右子树是不是平衡结点。此时我们将往函数TreeDepth输入左子树根结点(值为2的结点),需要遍历结点4、5、7。接下来判断以值为2的结点为根结点的子树是不是平衡树的时候,仍然会遍历结点4、5、7。毫无疑问,重复遍历同一个结点会影响性能。接下来我们寻找不需要重复遍历的算法。

法二:后序遍历

由于上述方法在求该结点的的左右子树深度时遍历一遍树,再次判断子树的平衡性时又遍历一遍树结构,造成遍历多次。因此方法二是一边遍历树一边判断每个结点是否具有平衡性

判断左子树和右子树是否是平衡二叉树,是的话更新深度

bool IsBalanced(TreeNode* pRoot,int &depth)
{
if(pRoot == NULL)
{
depth = 0;
return true;
}
int leftDepth,rightDepth;
bool left = IsBalanced(pRoot->left,leftDepth);
bool right = IsBalanced(pRoot->right,rightDepth);
if(left && right)
{
int dif = leftDepth - rightDepth;
if(dif <= 1 && dif >= -1)
{
depth = (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
return true;
}
}
return false;
}
bool IsBalanced_Solution(TreeNode* pRoot)
{
int depth = 0;
return IsBalanced(pRoot,depth);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: