-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnectNodes.cpp
48 lines (37 loc) · 1013 Bytes
/
connectNodes.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
#include <bits/stdc++.h>
/*
----------------- 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) {
queue<BinaryTreeNode<int>*> q;
q.push(root);
while(q.size()) {
BinaryTreeNode<int> *pre = NULL;
int sz = q.size();
for(int i=0; i<sz; i++) {
auto cur = q.front();
q.pop();
if(pre != NULL)
pre->next = cur;
pre = cur;
if(cur->left)
q.push(cur->left);
if(cur->right)
q.push(cur->right);
}
}
}