[LeetCode-116] Populating Next Right Pointers in Each Node

Populating Next Right Pointers in Each Node

Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

 

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

 

For example,
Given the following perfect binary tree,

         1
       /  \
      2    3
     / \  / \
    4  5  6  7

 

After calling your function, the tree should look like:

         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->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     void connect(TreeLinkNode *root) {
12         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         if (NULL == root) {
15             return;
16         }
17         vector<TreeLinkNode*> node_vec_a(1, root);
18         vector<TreeLinkNode*> node_vec_b;
19         bool flag = true;
20         vector<TreeLinkNode*> *pvec_last = NULL, *pvec_cur = NULL;
21         for (;;) {
22             if (flag) {
23                 pvec_last = &node_vec_a;
24                 pvec_cur = &node_vec_b;
25             } else {
26                 pvec_last = &node_vec_b;
27                 pvec_cur = &node_vec_a;
28             }
29             flag = !flag;
30             pvec_cur->clear();
31             if (0 == pvec_last->size()) {
32                 break;
33             }
34             for (vector<TreeLinkNode*>::iterator iter = pvec_last->begin();
35                     iter != pvec_last->end(); ++iter) {
36                 if (NULL != (*iter)->left) {
37                     pvec_cur->push_back((*iter)->left);
38                 }
39                 if (NULL != (*iter)->right) {
40                     pvec_cur->push_back((*iter)->right);
41                 }
42             }
43             for (vector<TreeLinkNode*>::iterator iter = pvec_cur->begin();
44                     iter != pvec_cur->end(); ++iter) {
45                 (*iter)->next = ((pvec_cur->end() == (iter + 1)) ? NULL : *(iter + 1));
46             }
47         }
48     }
49 };
View Code

 

posted on 2013-09-11 22:09  似溦若岚  阅读(138)  评论(0编辑  收藏  举报

导航