淘宝笔试题:树的层遍历

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

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

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

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

 1 struct SBinaryTreeNode // a node of the binary tree
 2 {
 3     int               m_nValue; // value of node
 4     SBinaryTreeNode  *m_pLeft;  // left child of node
 5     SBinaryTreeNode  *m_pRight; // right child of node
 6     SBinaryTreeNode  *m_pNext;
 7 };
 8 
 9 void LevelOder(SBinaryTreeNode * root)
10 {
11     if (!root)
12     {
13         return ;
14     }
15     
16     queue<SBinaryTreeNode*> q;
17     SBinaryTreeNode *p;
18     unsigned long i=1;
19     unsigned long l=2; //level of ..
20 
21     q.push(root);
22 
23     while(!q.empty())
24     {
25         p = q.front();
26 
27         if (p->m_pLeft)
28         {
29             q.push(p->m_pLeft);
30         }
31         if (p->m_pRight)
32         {
33             q.push(p->m_pRight);
34         }
35         q.pop();
36         if (i == l-1)
37         {
38             //tail of this level 
39             l<<=1;
40             p->m_pNext = NULL;
41         }
42         else
43         {
44             if (!q.empty())
45             {
46                 p->m_pNext = q.front();
47             }
48             else
49             {
50                 p->m_pNext = NULL;
51             }
52         }
53         ++i;
54     }
55 }

 时间复杂度为O(n),空间复杂度为O(2^(ceil(logn)))即拥有最多节点层;

posted @ 2013-04-11 12:50  legendmaner  阅读(261)  评论(0编辑  收藏  举报