-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPopulating Next Right Pointers in Each Node.cpp
94 lines (82 loc) · 2.35 KB
/
Populating Next Right Pointers in Each Node.cpp
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
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
// Optimal solution: iterative with constant space complexity.
// Use two pointers to traverse and connect node level by level.
class Solution {
public:
void connect(TreeLinkNode *root) {
if (root == nullptr) {
return;
}
TreeLinkNode *high = root;
TreeLinkNode *low = root->left;
while (low != nullptr) {
TreeLinkNode *cur = low;
while (high != nullptr) {
if (cur != high->left) {
cur->next = high->left;
cur = cur->next;
}
cur->next = high->right;
cur = cur->next;
high = high->next;
}
high = low;
low = high->left;
}
}
};
// Recursion: no explicit additional space.
class Solution {
public:
void connect(TreeLinkNode *root) {
if (root == nullptr) {
return;
}
if (root->left != nullptr) {
root->left->next = root->right;
}
if (root->right != nullptr && root->next != nullptr) {
root->right->next = root->next->left;
}
connect(root->right);
connect(root->left);
}
};
// Use extra space
class Solution {
public:
void connect(TreeLinkNode *root) {
queue<TreeLinkNode *> q;
int num_at_this_level, num_at_next_level = 0;
if (root == nullptr)
return;
num_at_this_level = 1;
q.push(root);
while (!q.empty()) {
TreeLinkNode *cur = q.front();
q.pop();
if (cur->left != nullptr) {
q.push(cur->left);
num_at_next_level++;
}
if (cur->right != nullptr) {
q.push(cur->right);
num_at_next_level++;
}
if (--num_at_this_level > 0) {
cur->next = q.front();
} else {
cur->next = nullptr;
num_at_this_level = num_at_next_level;
num_at_next_level = 0;
}
}
}
};