Skip to content

Commit 5d76284

Browse files
add level order tree construction and traversal implementation
1 parent adaa4d9 commit 5d76284

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

24binarytree/05treeFromLevelNodes.cpp

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#include<iostream>
2+
#include<queue>
3+
#include<vector>
4+
//using level order traversal coonstruct a tree
5+
using namespace std;
6+
class Node{
7+
public:
8+
int val;
9+
Node* left;
10+
Node* right;
11+
Node(int val){
12+
this->val = val;
13+
this->left = nullptr;
14+
this->right = nullptr;
15+
}
16+
};
17+
void levelOrderQueue(Node *root){
18+
queue<Node*> q;
19+
q.push(root);
20+
while(q.size()>0){
21+
Node* temp = q.front();
22+
q.pop();
23+
cout<<temp->val<<" ";
24+
if(temp->left!=nullptr) q.push(temp->left);
25+
if(temp->right!=nullptr) q.push(temp->right);
26+
}
27+
cout<<endl;
28+
}
29+
int main(){
30+
queue<Node*> q;
31+
vector<int> v = {1,2,3,4,5,INT_MIN,6,INT_MIN,INT_MIN,7,8,9,INT_MIN,INT_MIN,11}; //INT_MIN is used to represent NULL
32+
Node* root = new Node(v[0]);
33+
q.push(root);
34+
int i = 1,j = 2;
35+
while(i<v.size()){
36+
Node* temp = q.front();
37+
q.pop();
38+
if(v[i]!=INT_MIN){//non null value
39+
temp->left = new Node(v[i]);
40+
q.push(temp->left);
41+
}else {//for null value or INT_MIN though by default it will have nullptr
42+
temp->left = nullptr;
43+
}
44+
if(v[j]!=INT_MIN && j<v.size()){//non null value
45+
temp->right = new Node(v[j]);
46+
q.push(temp->right);
47+
}
48+
else {//for null value or INT_MIN though by default it will have nullptr
49+
temp->right = nullptr;
50+
}
51+
i+=2;
52+
j+=2;
53+
}
54+
levelOrderQueue(root);
55+
return 0;
56+
}

24binarytree/05treeFromLevelNodes.exe

176 KB
Binary file not shown.

0 commit comments

Comments
 (0)