-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path04_bst.cpp
More file actions
137 lines (123 loc) · 2.39 KB
/
04_bst.cpp
File metadata and controls
137 lines (123 loc) · 2.39 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
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
130
131
132
133
134
135
136
137
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
Node(int data)
{
this->data = data;
left = NULL;
right = NULL;
}
};
void traversal(Node* root)
{
if (root == NULL)
{
return;
}
else
{
cout << root->data << " ";
traversal(root->left);
traversal(root->right);
}
}
Node* insert(Node* &root, int x)
{
if (root == NULL)
{
root = new Node(x);
}
else if (x >= root->data)
{
root->right = insert(root->right, x);
}
else if (x < root->data)
{
root->left = insert(root->left, x);
}
return root;
}
int height(Node* root)
{
if (root == NULL)
{
return 0;
}
int left_subtree = 1+height(root->left);
int right_subtree = 1+height(root->right);
return max(left_subtree, right_subtree);
}
int minimum(Node* root)
{
if (root->left == NULL)
{
return root->data;
}
return min(minimum(root->left), root->data);
}
void search(Node* root, int key, bool &present)
{
if (root == NULL)
{
return;
}
if (root->data == key)
{
present = true;
}
else if (root->data > key)
{
search(root->left, key, present);
}
else if (root->data <= key)
{
search(root->right, key, present);
}
}
void mirror(Node* &root)
{
if (root == NULL)
{
return;
}
mirror(root->left);
mirror(root->right);
swap(root->left, root->right);
}
int main()
{
Node *root = NULL;
int n;
cout << "Enter the number of nodes to be inserted in the BST-\n";
cin >> n;
for (int i = 0; i < n; i++)
{
int element;
cout << "Enter the data value to be inserted-\n";
cin >> element;
insert(root, element);
}
cout << "Displaying the elements of the BST-\n";
traversal(root);
cout << endl;
cout << "Height of the tree is " << height(root) << endl;
cout << "Minimum value in the BST is " << minimum(root) << endl;
int key;
cout << "Enter the data value to be searched in the BST-\n";
cin >> key;
bool present = false;
search(root, key, present);
if (present == true)
{
cout << "Key is present in the BST!" << endl;
}
else
{
cout << "Key is not present in the BST!" << endl;
}
return 0;
}