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

[LeetCode] [LeetCode] Populating Next Right Pointers in Each Node II

时间:2015-01-18 17:05:52      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:

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

 1 /**
 2  * Definition for binary tree with next pointer.
 3  * struct TreeLinkNode {
 4  *  int val;
 5  *  TreeLinkNode *left, *right, *next;
 6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     TreeLinkNode *NextNode(TreeLinkNode *p) {
12         while (p) {
13             if (p->left) 
14                 return p->left;
15             if (p->right)
16                 return p->right;
17             p = p->next;
18         }
19         
20         return NULL;
21     }
22     
23     void connect(TreeLinkNode *root) {
24         if (root == NULL) return;
25         TreeLinkNode *level_begin = root;
26         while (level_begin) {
27             TreeLinkNode *cur = level_begin;
28             while (cur) {
29                 if (cur->left)
30                     cur->left->next = (cur->right != NULL) ? cur->right : NextNode(cur->next);
31                 if (cur->right)
32                     cur->right->next = NextNode(cur->next);
33                 cur = cur->next;
34             }
35             level_begin = NextNode(level_begin); //下一层的开始节点
36         }
37     }
38 };

 

[LeetCode] [LeetCode] Populating Next Right Pointers in Each Node II

标签:

原文地址:http://www.cnblogs.com/vincently/p/4231931.html

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