-
Notifications
You must be signed in to change notification settings - Fork 0
/
populating-next-right-pointers-in-each-node-ii.cc
81 lines (73 loc) · 1.55 KB
/
populating-next-right-pointers-in-each-node-ii.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
struct TreeLinkNode {
int val;
TreeLinkNode *left, *right, *next;
TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};
class Solution {
public:
#if 1
void connect(TreeLinkNode *root) {
if (root == NULL) return;
TreeLinkNode *p = root;
root->next = NULL;
// 层序遍历,遍历一层时把下一层的节点连接起来,并记录下一层的第一个节点
while (p != NULL) {
TreeLinkNode *next = NULL;
TreeLinkNode *prev = NULL;
while (p != NULL) {
if (p->left != NULL) {
if (next == NULL) {
next = p->left;
} else {
prev->next = p->left;
}
prev = p->left;
}
if (p->right != NULL) {
if (next == NULL) {
next = p->right;
} else {
prev->next = p->right;
}
prev = p->right;
}
p = p->next;
}
p = next;
}
}
#else
void connect(TreeLinkNode *root) {
if (root == NULL) return;
TreeLinkNode *next_level_start = NULL;
TreeLinkNode *p = root;
TreeLinkNode *prev = NULL;
root->next = NULL;
while (p != NULL) {
if (p->left != NULL) {
if (prev != NULL) {
prev->next = p->left;
} else {
next_level_start = p->left;
}
prev = p->left;
}
if (p->right != NULL) {
if (prev != NULL) {
prev->next = p->right;
} else {
next_level_start = p->right;
}
prev = p->right;
}
p = p->next;
if (p == NULL) {
p = next_level_start;
next_level_start = NULL;
prev = NULL;
}
}
}
#endif
};