码迷,mamicode.com
首页 > 其他好文 > 详细

Populating Next Right Pointers in Each Node II

时间:2015-06-20 16:53:04      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:

Description:

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

For example,
Given the following binary tree,

         1
       /        2    3
     / \        4   5    7

 

After calling your function, the tree should look like:

         1 -> NULL
       /        2 -> 3 -> NULL
     / \        4-> 5 -> 7 -> NULL

Code:

 1  void connect(TreeLinkNode *root) {
 2         if (!root)
 3             return ;
 4         deque<TreeLinkNode*>a;
 5         deque<TreeLinkNode*>b;
 6         a.push_back(root);
 7         
 8         while (!a.empty())
 9         {
10             while (!a.empty())
11             {
12                 TreeLinkNode* p = a.front();
13                 a.pop_front();
14                 if(p->left)
15                     b.push_back(p->left);
16                 if(p->right)
17                     b.push_back(p->right);
18                
19                if (a.empty())  
20                     p->next = NULL; 
21                else
22                     p->next = a.front();
23             }
24             a = b;
25             b.clear();
26         }
27     }

 

Populating Next Right Pointers in Each Node II

标签:

原文地址:http://www.cnblogs.com/happygirl-zjj/p/4590649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!