您的位置:首页 > 其它

淘宝笔试题:树的层遍历

2013-04-11 12:50 162 查看
淘宝笔试题:对于一颗完全二叉树,要求给所有节点加上一个pNext指针,指向同一层的相邻节点;如果当前节点已经是该层的最后一个节点,则将pNext指针指向NULL;给出程序实现,并分析时间复杂度和空间复杂度。

题目的只是层遍历的变形。。

朋友过来一起玩了几天,不亦乐乎。。。

结果写些code都是一堆一堆bug。。。

struct SBinaryTreeNode // a node of the binary tree
{
int               m_nValue; // value of node
SBinaryTreeNode  *m_pLeft;  // left child of node
SBinaryTreeNode  *m_pRight; // right child of node
SBinaryTreeNode  *m_pNext;
};

void LevelOder(SBinaryTreeNode * root)
{
if (!root)
{
return ;
}

queue<SBinaryTreeNode*> q;
SBinaryTreeNode *p;
unsigned long i=1;
unsigned long l=2; //level of ..

q.push(root);

while(!q.empty())
{
p = q.front();

if (p->m_pLeft)
{
q.push(p->m_pLeft);
}
if (p->m_pRight)
{
q.push(p->m_pRight);
}
q.pop();
if (i == l-1)
{
//tail of this level
l<<=1;
p->m_pNext = NULL;
}
else
{
if (!q.empty())
{
p->m_pNext = q.front();
}
else
{
p->m_pNext = NULL;
}
}
++i;
}
}


时间复杂度为O(n),空间复杂度为O(2^(ceil(logn)))即拥有最多节点层;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: