-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtraversal_levelorder.cpp
107 lines (89 loc) · 2.49 KB
/
traversal_levelorder.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// print the level order traversal of a BST
#include <iostream>
#include <queue>
using namespace std;
struct node{
int data;
struct node* left;
struct node* right;
node(int value){
data = value;
left = NULL;
right = NULL;
}
};
// Approach2 : iterative level order traversal , print BT from queue
// insert the root and a null element into the queue ( null element acts as a delimiter).
// Next pop from the top of the queue and add its left and right nodes to the end of the queue and then print the top of the queue.
// Continue this process till the queues become empty.
int height(node *currnode ){
if(currnode==NULL) return 0;
return 1+ max(height(currnode-> left) , height(currnode->right));
}
void printq(queue<node*> q){
queue<node*> qcopy = q;
cout<<"\n print Queue ";
while(!qcopy.empty()){
cout << " \t " << qcopy.front();
qcopy.pop();
}
cout << '\n';
}
void levelordertraversal(node* root){
int h = height(root);
cout << " height "<< h << endl;
if(root == NULL ) return;
queue<node*> q; // empty queue
node* curr; // node to store front element
q.push(root);
q.push(NULL);
while(q.size()>1){
curr = q.front();
q.pop();
if(curr ==NULL){
q.push(NULL);
cout << "\n";
}else{
if(curr->left) q.push(curr->left);
if(curr->right) q.push(curr->right);
cout << curr->data << " ";
}
}
printq(q);
}
//approach 1 : Recursive level order traversal , print keys
// void levelorderprint(node* root , int level){
// if(root==NULL) return;
// if(level==1){
// cout << root->data << " ";
// }else if(level>1){
// levelorderprint(root->left, level-1);
// levelorderprint(root->right, level -1);
// }
// }
// void levelordertraversal(node* root){
// int h = height(root);
// cout << " height "<< h << endl;
// for( int i=1 ;i<= h ;i++){
// levelorderprint(root,i);
// cout<<endl;
// }
// }
int main() {
struct node* root = new node(1);
root->left = new node(2);
root->left->left = new node(3);
root->left->right = new node(4);
root->right = new node(5);
root->right->left = new node(6);
cout << "BST ";
levelordertraversal(root);
return 0;
}
// g++ levelorder_traversal.cpp -o levelorder_traversal.out
// ./levelorder_traversal.out
// output
//BST height 3
//1
//2 5
//3 4 6