-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPopulatingNextRightPointsinEachNode.cpp
More file actions
119 lines (90 loc) · 2.45 KB
/
PopulatingNextRightPointsinEachNode.cpp
File metadata and controls
119 lines (90 loc) · 2.45 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// 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) {}
};
class Solution {
public:
void connect(TreeLinkNode *root) {
TreeLinkNode *prev = NULL;
TreeLinkNode *curr = NULL;
int seq_curr = 1;
int seq_next = 1;
while (seq_curr <= seq_next) {
curr = GetNextNode(root, seq_curr);
if (curr && (curr->left || curr->right)) {
seq_next = seq_curr * 2 + 1;
}
if (prev)
prev->next = curr;
if (curr)
prev = curr;
if (seq_curr == 1 || (seq_curr & (seq_curr - 1) == 0)) {
prev = NULL;
}
seq_curr++;
}
return;
}
TreeLinkNode* GetNextNode(TreeLinkNode* root, int seq_req) {
int seq_init = 1;
while (seq_init < seq_req) {
if (IsInLeft(seq_init, seq_req)) {
root = root->left;
seq_init = seq_init * 2;
}
else {
root = root->right;
seq_init = seq_init * 2 + 1;
}
if (!root)
break;
}
return root;
}
//whether require sequence(node) is in current sequence(node)'s left subtree.
bool IsInLeft(int seq_cur, int seq_req) {
assert(seq_cur <= seq_req);
while (seq_req > seq_cur * 2 + 1)
seq_req = seq_req / 2;
return seq_req % 2? true : false;
}
};
//Populating Next Right Points in Each Node 1
class Solution {
public:
void connect(TreeLinkNode *root) {
TreeLinkNode* lhs = NULL;
TreeLinkNode* rhs = NULL;
if (!root)
goto out;
lhs = root->left;
rhs = root->right;
while (lhs && rhs) {
lhs->next = rhs;
lhs = lhs->right;
rhs = rhs->left;
}
connect(root->left);
connect(root->right);
out:
return;
}
};
//Populating Next Right Points in Each Node 2
class Solution {
public:
void connect(TreeLinkNode *root) {
TreeLinkNode* lhs = NULL;
TreeLinkNode* rhs = NULL;
if (root == NULL)
goto out;
lhs = root->left;
rhs = root->right;
connect(root->left);
connect(root->right);
out:
return;
}
};