-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnext_right_pointers.cpp
More file actions
45 lines (42 loc) · 1.3 KB
/
Copy pathnext_right_pointers.cpp
File metadata and controls
45 lines (42 loc) · 1.3 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
/**
* 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) {
if (root != nullptr){
std::queue<TreeLinkNode *> q;
std::queue<TreeLinkNode *> temp;
temp.push(root->right);
temp.push(root->left);
while (!temp.empty()){
q.swap(temp);
TreeLinkNode *n = nullptr;
while (!q.empty()) {
TreeLinkNode *t = q.front();
if (t != nullptr){
temp.push(t->right);
temp.push(t->left);
}
n = myConnect(t, n);
q.pop();
}
}
}
}
TreeLinkNode* myConnect(TreeLinkNode *node, TreeLinkNode *next) {
if (node == nullptr) return next;
node->next = next;
return node;
}
// TreeLinkNode* getNextRightMost(TreeLinkNode *node) {
// if (node == nullptr) return nullptr;
// if (node->right != nullptr) return node->right;
// else return node->left;
// }
};