-
Notifications
You must be signed in to change notification settings - Fork 0
/
printBST_BFS.cc
59 lines (52 loc) · 1.26 KB
/
printBST_BFS.cc
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
#include <iostream>
#include <queue>
using namespace std;
typedef struct elementT {
struct elementT* left;
struct elementT* right;
int data;
} element;
void printLevel(queue<element *>*firstQ, queue<element *>*secondQ) {
element *ele;
while(!(*firstQ).empty()) {
ele = (*firstQ).front();
(*firstQ).pop();
cout << ele->data << " ";
if(ele->left)
(*secondQ).push(ele->left);
if(ele->right)
(*secondQ).push(ele->right);
}
cout << endl;
}
void printBFS(element *root) {
queue<element *>firstQ;
queue<element *>secondQ;
if(!root)
return;
firstQ.push(root);
element *ele;
while(!(firstQ.empty() && secondQ.empty())) {
if(!firstQ.empty()) {
printLevel(&firstQ, &secondQ);
} else if(!secondQ.empty()) {
printLevel(&secondQ, &firstQ);
}
}
}
element *makeNode(int d) {
element *ele = new element();
ele->data = d;
return ele;
}
main()
{
element *root = makeNode(50);
root->left = makeNode(25);
root->right = makeNode(75);
root->left->left = makeNode(12);
root->left->right = makeNode(35);
root->right->left = makeNode(60);
root->right->right = makeNode(80);
printBFS(root);
}