-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathconnectNodesAtSameLevel.cpp
More file actions
39 lines (31 loc) · 910 Bytes
/
connectNodesAtSameLevel.cpp
File metadata and controls
39 lines (31 loc) · 910 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
32
33
34
35
36
37
38
39
class Solution
{
public:
//Function to connect nodes at same level.
void connect(Node *root)
{
// Your Code Here
if(!root)
return;
root -> nextRight = nullptr;
queue<Node*> q;
q.push(root);
Node* temp;
while(!q.empty()){
int size = q.size();
for(int i = 0; i < size; i++){
Node* prev = temp;
temp = q.front();
q.pop();
if(i > 0){
prev -> nextRight = temp;
}
if(temp -> left)
q.push(temp -> left);
if(temp -> right)
q.push(temp -> right);
temp -> nextRight = nullptr;
}
}
}
};