-
Notifications
You must be signed in to change notification settings - Fork 0
/
116.populating-next-right-pointers-in-each-node.cpp
69 lines (62 loc) · 1.49 KB
/
116.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
/*
* @lc app=leetcode id=116 lang=cpp
*
* [116] Populating Next Right Pointers in Each Node
*/
// @lc code=start
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node* _left, Node* _right, Node* _next)
: val(_val), left(_left), right(_right), next(_next) {}
};
*/
class Solution {
public:
void bfs(queue<Node*> &l){
queue<Node*>k;
vector<Node*> v;
while(!l.empty()){
if(l.front()->right||l.front()->left){
k.push(l.front()->left);
k.push(l.front()->right);
v.push_back(l.front()->left);
v.push_back(l.front()->right);
}
l.pop();
}
if(v.size()>1){
for(int i=1; i<v.size(); i++){
v[i-1]->next = v[i];
}
v[v.size()-1]->next = NULL;
}
l.swap(k);
}
Node* connect(Node* root) {
if(!root){
return root;
}
if(!root->left){
root->next = NULL;
return root;
}
queue<Node*> l;
l.push(root->left);
root->left->next = root->right;
root->right->next = NULL;
l.push(root->right);
while(!l.empty()){
bfs(l);
}
return root;
}
};
// @lc code=end