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

Populating Next Right Pointers in Each Node II

时间:2014-08-15 12:07:08      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   strong   for   ar   cti   

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

思路:自顶向下链接二叉树的每一层,当处理到第i层时,第i-1层的所有节点已经构成一个单向链表。依次遍历第i-1层便可顺利完成对第i层的链接。因为去掉了输入是完全二叉树的限定,因此内层循环比完全二叉树的会稍微复杂一些。

 1 class Solution {
 2 public:
 3     void connect( TreeLinkNode *root ) {
 4         TreeLinkNode *head = root;
 5         while( head ) {
 6             TreeLinkNode *newHead = 0, *prevNode = 0;
 7             while( head ) {
 8                 if( head->left ) {
 9                     if( !prevNode ) {
10                         newHead = prevNode = head->left;
11                     } else {
12                         prevNode->next = head->left;
13                         prevNode = prevNode->next;
14                     }
15                 }
16                 if( head->right ) {
17                     if( !prevNode ) {
18                         newHead = prevNode = head->right;
19                     } else {
20                         prevNode->next = head->right;
21                         prevNode = prevNode->next;
22                     }
23                 }
24                 head = head->next;
25             }
26             head = newHead;
27         }
28         return;
29     }
30 };

 

Populating Next Right Pointers in Each Node II,布布扣,bubuko.com

Populating Next Right Pointers in Each Node II

标签:style   blog   color   io   strong   for   ar   cti   

原文地址:http://www.cnblogs.com/moderate-fish/p/3914121.html

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