-
Notifications
You must be signed in to change notification settings - Fork 0
/
054_ConnectNodesAtSameLevel.cpp
55 lines (45 loc) · 1.06 KB
/
054_ConnectNodesAtSameLevel.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
#include<bits/stdc++.h>
using namespace std;
/*
----------------- Binary Tree node class for reference -----------------
*/
template <typename T>
class BinaryTreeNode {
public :
T data;
BinaryTreeNode<T> *left;
BinaryTreeNode<T> *right;
BinaryTreeNode<T> *next;
BinaryTreeNode(T data) {
this -> data = data;
left = NULL;
right = NULL;
next = NULL;
}
};
void connectNodes(BinaryTreeNode< int > *root) {
// Write your code here.
// method-1
queue<BinaryTreeNode< int > *> Q;
Q.push(root);
while(!Q.empty()){
int k=Q.size();
vector<BinaryTreeNode< int >*> temp;
for(int i=0; i<k; i++){
BinaryTreeNode< int > *curr=Q.front();
Q.pop();
if(curr->left){
Q.push(curr->left);
temp.push_back(curr->left);
}
if(curr->right){
Q.push(curr->right);
temp.push_back(curr->right);
}
}
int n=temp.size();
for(int i=0;i<n-1; i++){
temp[i]->next=temp[i+1];
}
}
}