-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path116.cpp
More file actions
31 lines (31 loc) · 876 Bytes
/
116.cpp
File metadata and controls
31 lines (31 loc) · 876 Bytes
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
#include <queue>
using namespace std;
struct Node {
int val;
Node* left;
Node* right;
Node* next;
Node() : val(0), left(nullptr), right(nullptr), next(nullptr) {}
Node(int _val) : val(_val), left(nullptr), right(nullptr), next(nullptr) {}
Node(int _val, Node* _left, Node* _right, Node* _next) : val(_val), left(_left), right(_right), next(_next) {}
};
class Problem116 {
public:
Node* connect(Node* root) {
if (!root) return nullptr;
queue<Node*> q;
q.push(root);
int counter = 2;
while(!q.empty()){
Node* node = q.front();
q.pop();
if ((counter & counter-1) != 0) node->next = q.front();
if (node->left){
q.push(node->left);
q.push(node->right);
}
counter++;
}
return root;
}
};