-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST.cpp
123 lines (98 loc) · 1.92 KB
/
BST.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
#include <iostream>
using namespace std;
enum traversal_t { inorder, preorder, postorder};
struct Node{
int data;
Node* left;
Node* right;
//constructor
Node(int val): data(val), left(NULL), right(NULL) {}
};
class BST{
private:
Node* treeRoot;
Node* insert(Node* root, int data);
void postorder_trav(Node* root);
void inorder_trav(Node* root);
void preorder_trav(Node* root);
public:
//constructor
BST(){
treeRoot = NULL;
}
void insert(int data);
void print(traversal_t val);
Node* getRoot() {
return treeRoot;
}
};
void BST::insert(int data){
if(treeRoot == NULL){
treeRoot = new Node(data);
}
else{
this->insert(treeRoot, data);
}
}
Node* BST::insert(Node* root, int data){
if(root == NULL){
root = new Node(data);
}
else if(data <= root->data){
root->left = insert(root->left, data);
}
else {
root->right = insert(root->right, data);
}
return root;
}
void BST::print(traversal_t val){
switch(val) {
case inorder:
cout << "printing inorder" << endl;
inorder_trav(treeRoot);
cout << endl;
break;
case preorder:
cout << "printing preorder" << endl;
preorder_trav(treeRoot);
cout << endl;
break;
case postorder:
cout << "printing postorder" << endl;
postorder_trav(treeRoot);
cout << endl;
break;
}
}
void BST::postorder_trav(Node* root){
if(root == NULL)
return;
postorder_trav(root->left);
postorder_trav(root->right);
cout << root->data << " ";
}
void BST::inorder_trav(Node* root){
if(root == NULL)
return;
inorder_trav(root->left);
cout << root->data << " ";
inorder_trav(root->right);
}
void BST::preorder_trav(Node* root){
if (root == NULL)
return;
cout << root->data << " ";
preorder_trav(root->left);
preorder_trav(root->right);
}
int main(){
BST tree;
tree.insert(10);
tree.insert(5);
tree.insert(1);
tree.insert(15);
tree.print(postorder);
tree.print(preorder);
tree.print(inorder);
}