-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path116.cpp
More file actions
44 lines (43 loc) · 1.2 KB
/
Copy path116.cpp
File metadata and controls
44 lines (43 loc) · 1.2 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
/**
* 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) return;
queue<pair<TreeLinkNode*, int>> q;
pair<TreeLinkNode*, int> previous = make_pair(nullptr, 0);
q.push(make_pair(root, 0));
while(!q.empty()){
auto top_e = q.front();
q.pop();
if(top_e.first != NULL){
q.push(make_pair(top_e.first->left, top_e.second+1));
q.push(make_pair(top_e.first->right, top_e.second+1));
}
if(previous.first != NULL && previous.second==top_e.second) previous.first->next = top_e.first;
previous = top_e;
}
}
};
/* Recommended solution
void connect(TreeLinkNode *root) {
if (root == NULL) return;
TreeLinkNode *pre = root;
TreeLinkNode *cur = NULL;
while(pre->left) {
cur = pre;
while(cur) {
cur->left->next = cur->right;
if(cur->next) cur->right->next = cur->next->left;
cur = cur->next;
}
pre = pre->left;
}
}
*/