8000 3 · javasharper/leetcode@3512997 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3512997

Browse files
committed
3
1 parent 405b552 commit 3512997

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
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;
30+
}
31+
else {
32+
next_link_head = link_head->right;
33+
next_link_node = next_link_head;
34+
}
35+
}
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;
49+
}
50+
link_head = link_head->next;
51+
}
52+
link_head = next_link_head;
53+
}
54+
}
55+
};
56+

0 commit comments

Comments
 (0)
0