CoderJesse  
wangjiexi@CS.PKU
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

二叉树的广度优先周游。需要注意的是每一行结束的那个节点需要连接到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(root == NULL)
15             return;
16         queue<TreeLinkNode*> Q;
17         Q.push(root);
18         int c = 0;
19         int size = 1;
20         while(!Q.empty())
21         {
22             TreeLinkNode* tmp =  Q.front();
23             Q.pop();
24             if(tmp->left != NULL)
25             {
26                 Q.push( tmp->left);
27                 Q.push( tmp->right);
28             }
29             c++;
30             if(c == size)
31             {
32                 tmp->next = NULL;
33                 c = 0;
34                 size *= 2;
35             }
36             else
37             {
38                 tmp->next =  Q.front();
39             }
40         }
41     }
42 };

 

posted on 2013-02-28 12:30  CoderJesse  阅读(128)  评论(0)    收藏  举报