-
Notifications
You must be signed in to change notification settings - Fork 0
/
printBST.cc
129 lines (121 loc) · 2.74 KB
/
printBST.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
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <stdio.h>
#include <stdlib.h>
#include <stack>
#include <queue>
#include <iostream>
using namespace std;
typedef struct elementT {
struct elementT *left;
struct elementT *right;
int data;
} element;
void printBSTRecursive(element *root) {
if(!root)
return;
printBSTRecursive(root->left);
printf("%d ", root->data);
printBSTRecursive(root->right);
}
void printBSTIterative(element *root) {
stack<element *>s;
element *curr = root;
while(true) {
if(curr) {
s.push(curr);
curr = curr->left;
} else {
if(s.empty())
break;
else {
element *t = s.top();
s.pop();
printf("%d ", t->data);
curr = t->right;
}
}
}
}
void BFS(element *root) {
queue<element *>q;
q.push(root);
element *curr;
while(true) {
if(q.empty())
break;
curr = q.front();
if(curr) {
q.pop();
printf("%d ", curr->data);
}
if(curr->left)
q.push(curr->left);
if(curr->right)
q.push(curr->right);
}
}
void BFSZigZag(element *root) {
queue<element *>q;
q.push(root);
element *curr;
int level = 1;
int nCurrNode = 1, nNextLev = 0;
stack<int>s;
while(!q.empty()) {
curr = q.front();
if(curr) {
if(level % 2 == 1)
printf("%d ", curr->data);
else
s.push(curr->data);
q.pop();
}
nCurrNode--;
if(curr->left) {
nNextLev++;
q.push(curr->left);
}
if(curr->right) {
nNextLev++;
q.push(curr->right);
}
if(nCurrNode <= 0) {
if(level % 2 == 0) {
while(!s.empty()) {
printf("%d ", s.top());
s.pop();
}
printf("\n");
} else
printf("\n");
nCurrNode = nNextLev;
nNextLev = 0;
level++;
}
}
}
element *makeNode(int d) {
element *ele = (element *)malloc(sizeof(element));
if(!ele)
return NULL;
ele->data = d;
return ele;
}
main()
{
element *root = makeNode(50);
if(root) {
root->left = makeNode(25);
root->left->left = makeNode(12);
root->left->left->left = makeNode(6);
root->right = makeNode(75);
root->right->left = makeNode(62);
root->right->right = makeNode(80);
}
//printBSTRecursive(root);
//printf("\n");
//printBSTIterative(root);
//printf("\n");
BFS(root);
printf("\n");
BFSZigZag(root);
}