[LeetCode-117] Populating Next Right Pointers in Each Node II
Populating Next Right Pointers in Each Node II
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
其实貌似116的case里包含这种情况了。。。同一份代码~LOL~~~
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 };