-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Search Tree.cpp
110 lines (95 loc) · 2.04 KB
/
Binary Search Tree.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
// Tree - Binary Search Tree
// Insertion in BST
// Searching in BST
// InOrder Display in BST
// PreOrder Display in BST
// PostOrder Display in BST
#include<iostream>
#include<string>
using namespace std;
struct node{
int data;
node* left;
node* right;
};
// Insertion in BST
node* insertion(node* root, int item){
if (!root){
node* newnode = new node;
newnode->data = item;
newnode->left = NULL;
newnode->right = NULL;
return newnode;
}
if (item < root->data){
root->left = insertion(root->left, item);
}
else{
root->right = insertion(root->right, item);
}
return root;
}
// Searching in BST
bool search(node *root, int data){
if(root == NULL){
return false;
}
if(root->data == data){
return true;
}
else if(root->data > data){
return search(root->left, data);
}
else{
return search(root->right, data);
}
}
// InOrder Display in BST
void InorderDisplay(node* root) {
if (root != NULL) {
InorderDisplay(root->left);
cout << root->data << "->";
InorderDisplay(root->right);
}
}
// PreOrder Display in BST
void preOrderDisplay(node* root) {
if (root != NULL) {
cout << root->data << "->";
preOrderDisplay(root->left);
preOrderDisplay(root->right);
}
}
// PostOrder Display in BST
void postOrderDisplay(node* root) {
if (root != NULL) {
postOrderDisplay(root->left);
postOrderDisplay(root->right);
cout << root->data << "->";
}
}
// Main function
int main() {
node *root = NULL;
root = insertion(root ,2);
insertion(root , 5);
insertion(root , 1);
cout << "In Order Display" << endl;
InorderDisplay(root);
cout << endl;
cout << "Pre Order Display" << endl;
preOrderDisplay(root);
cout << endl;
cout << "Post Order Display" << endl;
postOrderDisplay(root);
cout << endl;
cout << endl;
bool found = search(root, 3);
if(found){
cout << "Value Found!";
}
else{
cout << "Value Not Found!";
}
cout << endl;
}