-
Notifications
You must be signed in to change notification settings - Fork 0
/
q14.cpp
124 lines (112 loc) · 2 KB
/
q14.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*
/*
/* Design, develop, and execute a program in C++ to create a class
/* called BIN_TREE that represents a Binary Tree, with member
/* functions to perform inorder, preorder and postorder traversals.
/* Create a BIN_TREE object and demonstrate the traversals.
/*
*/
#include <iostream>
using namespace std;
class Node {
public:
int val;
Node *right, *left;
Node() {
right = NULL;
left = NULL;
}
};
class BTree {
Node *root;
public:
BTree() {
root = NULL;
}
void inorder() {
this->inorder(root);
}
void inorder(Node *n) {
if(n != NULL) {
this->inorder(n->left);
cout << " " << n->val;
this->inorder(n->right);
}
}
void preorder() {
this->preorder(root);
}
void preorder(Node *n) {
if(n != NULL) {
cout << " " << n->val;
this->preorder(n->left);
this->preorder(n->right);
}
}
void postorder() {
this->postorder(root);
}
void postorder(Node *n) {
if(n != NULL) {
this->preorder(n->left);
this->preorder(n->right);
cout << " " << n->val;
}
}
void insert(int key) {
Node *n = new Node();
n->val = key;
Node *r = root, *prev = NULL;
if(r == NULL)
root = n;
else {
while(r != NULL) {
prev = r;
if(n->val > r->val)
r = r->right;
else if(n->val <= r->val)
r = r->left;
}
if(n->val > prev->val)
prev->right = n;
else
prev->left = n;
}
}
};
int main() {
BTree b;
int item;
cout << "\n Enter";
cout << "\n i to Insert";
cout << "\n p for Preorder";
cout << "\n n for Inorder";
cout << "\n o for Postorder";
do {
char choice;
cout << endl << " >> ";
cin >> choice;
switch(choice) {
case 'i':
cout << " Enter node to insert: ";
cin >> item;
b.insert(item);
break;
case 'n':
cout << endl << " Inorder: ";
b.inorder();
break;
case 'p':
cout << endl << " Preorder: ";
b.preorder();
break;
case 'o':
cout << endl << " Postorder: ";
b.postorder();
break;
default:
cout << endl << endl;
return 0;
}
} while(1);
}