-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12_BST.cpp
More file actions
79 lines (65 loc) · 1.36 KB
/
12_BST.cpp
File metadata and controls
79 lines (65 loc) · 1.36 KB
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
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
class node {
public:
int data;
node *left, *right;
node(int data) {
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
void insert(node *&root, int data) {
if (root == NULL) {
root = new node(data);
return;
}
if (data <= root->data) {
insert(root->left, data);
} else {
insert(root->right, data);
}
}
void inOrder(node *root) {
if (root != NULL) {
inOrder(root->left);
cout << root->data << " ";
inOrder(root->right);
}
return;
}
void preOrder(node *root) {
if (root != NULL) {
cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}
return;
}
void postOrder(node *root) {
if (root != NULL) {
postOrder(root->left);
postOrder(root->right);
cout << root->data << " ";
}
return;
}
int main() {
node *root = NULL;
int data;
cout << "Enter datas to create a BST. Enter -1 to Terminate: ";
cin >> data;
while (data != -1) {
insert(root, data);
cin >> data;
}
cout << "\nIn Order Traversal: ";
inOrder(root);
cout << "\nPre Order Traversal: ";
preOrder(root);
cout << "\nPost Order Traversal: ";
postOrder(root);
return 0;
}