|
9 | 9 | class Solution {
|
10 | 10 | public:
|
11 | 11 | void connect(TreeLinkNode *root) {
|
12 |
| - // Start typing your C/C++ solution below |
13 |
| - // DO NOT write int main() function |
14 |
| - |
15 |
| - TreeLinkNode *link_head = root; |
16 |
| - |
17 |
| - while (link_head) { |
18 |
| - TreeLinkNode *next_link_head = NULL; |
19 |
| - TreeLinkNode *next_link_node = NULL; |
20 |
| - |
21 |
| - while (link_head) { |
22 |
| - if (link_head->left) { |
23 |
| - next_link_head = link_head->left; |
24 |
| - next_link_node = next_link_head; |
25 |
| - } |
26 |
| - if (link_head->right) { |
27 |
| - if (next_link_node) { |
28 |
| - next_link_node->next = link_head->right; |
29 |
| - next_link_node = next_link_node->next; |
| 12 | + if (root == NULL) { |
| 13 | + return; |
| 14 | + } |
| 15 | + TreeLinkNode* leftmost = root; |
| 16 | + while (leftmost) { |
| 17 | + TreeLinkNode* node = leftmost; |
| 18 | + TreeLinkNode* prev = NULL; |
| 19 | + leftmost = NULL; |
| 20 | + while (node) { |
| 21 | + if (node->left) { |
| 22 | + if (leftmost == NULL) { |
| 23 | + leftmost = node->left; |
30 | 24 | }
|
31 |
| - else { |
32 |
| - next_link_head = link_head->right; |
33 |
| - next_link_node = next_link_head; |
| 25 | + if (prev == NULL) { |
| 26 | + prev = node->left; |
| 27 | + } else { |
| 28 | + prev->next = node->left; |
| 29 | + prev = node->left; |
34 | 30 | }
|
35 | 31 | }
|
36 |
| - if (next_link_head) break; |
37 |
| - link_head = link_head->next; |
38 |
| - } |
39 |
| - if (next_link_head == NULL) break; |
40 |
| - |
41 |
| - while (link_head->next) { |
42 |
| - if (link_head->next->left) { |
43 |
| - next_link_node->next = link_head->next->left; |
44 |
| - next_link_node = next_link_node->next; |
45 |
| - } |
46 |
| - if (link_head->next->right) { |
47 |
| - next_link_node->next = link_head->next->right; |
48 |
| - next_link_node = next_link_node->next; |
| 32 | + if (node->right) { |
| 33 | + if (leftmost == NULL) { |
| 34 | + leftmost = node->right; |
| 35 | + } |
| 36 | + if (prev == NULL) { |
| 37 | + prev = node->right; |
| 38 | + } else { |
| 39 | + prev->next = node->right; |
| 40 | + prev = node->right; |
| 41 | + } |
49 | 42 | }
|
50 |
| - link_head = link_head->next; |
| 43 | + node = node->next; |
51 | 44 | }
|
52 |
| - link_head = next_link_head; |
53 | 45 | }
|
54 | 46 | }
|
55 | 47 | };
|
56 |
| - |
0 commit comments