CoderJesse  
wangjiexi@CS.PKU
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     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         TreeLinkNode* mostLeft = root;
19         bool hasMostLeft = true;
20         while(!Q.empty())
21         {
22             TreeLinkNode* tmp =  Q.front();
23             Q.pop();
24             if(tmp == mostLeft)
25             {
26                 hasMostLeft = false;
27                 mostLeft = NULL;
28             }
29             
30             if(tmp->left != NULL)
31             {
32                 Q.push( tmp->left);
33                 if(hasMostLeft == false)
34                 {
35                     mostLeft = tmp->left;
36                     hasMostLeft = true;
37                 }
38             }
39             if(tmp->right != NULL)
40             {
41                 Q.push( tmp->right);
42                 if(hasMostLeft == false)
43                 {
44                     mostLeft = tmp->right;
45                     hasMostLeft = true;
46                 }
47             }
48 
49             if(Q.empty())
50                 tmp->next =  NULL;
51             else if(Q.front() != mostLeft)
52                 tmp->next =  Q.front();
53             else
54                 tmp->next =  NULL;
55         }
56     }
57 };

 

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