-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPopulating Next Right Pointers in Each Node II.cpp
92 lines (84 loc) · 2.74 KB
/
Populating Next Right Pointers in Each Node II.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
// https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
/**
* 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) {}
* };
*/
// Iterative solution: use O(1) space
class Solution {
public:
void connect(TreeLinkNode *root) {
if (root == nullptr) {
return;
}
TreeLinkNode *cur = root; // node in the current level
TreeLinkNode *head = nullptr; // the first node in the next level
TreeLinkNode *prev = nullptr; // the node by which the current processed node is pointed
while (cur != nullptr) {
while (cur != nullptr) {
if (cur->left != nullptr) {
if (prev != nullptr) {
prev->next = cur->left;
} else {
head = cur->left;
}
prev = cur->left;
}
if (cur->right != nullptr) {
if (prev != nullptr) {
prev->next = cur->right;
} else {
head = cur->right;
}
prev = cur->right;
}
cur = cur->next;
}
cur = head;
head = nullptr;
prev = nullptr;
}
}
};
// Recursion: still use O(n) extra space
class Solution {
public:
void connect(TreeLinkNode *root) {
if (root == nullptr) {
return;
}
// assemble right
if (root->right != nullptr) {
for (TreeLinkNode *nd = root->next; nd != nullptr; nd = nd->next) {
if (nd->left != nullptr) {
root->right->next = nd->left;
break;
} else if (nd->right != nullptr) {
root->right->next = nd->right;
break;
}
}
connect(root->right);
}
// assemble left
if (root->left != nullptr) {
if (root->right != nullptr) {
root->left->next = root->right;
} else {
for (TreeLinkNode *nd = root->next; nd != nullptr; nd = nd->next) {
if (nd->left != nullptr) {
root->left->next = nd->left;
break;
} else if (nd->right != nullptr) {
root->left->next = nd->right;
break;
}
}
}
connect(root->left);
}
}
};