-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgB_a6_BSTops.cpp
142 lines (118 loc) · 2.82 KB
/
gB_a6_BSTops.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#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;
}
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) // Insert smaller values to the left
{
root->left = insert(root->left, x);
}
else // Insert greater or equal values to the right
{
root->right = insert(root->right, x);
}
return root;
}
int height(Node* root)
{
if (root == NULL)
{
return 0; // Height of an empty tree is 0
}
int left_subtree = height(root->left);
int right_subtree = height(root->right);
return max(left_subtree, right_subtree) + 1;
}
int minimum(Node* root)
{
if (root == NULL)
{
cout << "Tree is empty!" << endl;
return -1; // Return an invalid value for empty tree
}
while (root->left != NULL) // Traverse to the leftmost node
{
root = root->left;
}
return root->data;
}
bool searchInBinaryTree(Node* root, int key) {
if (root == NULL) {
return false;
}
if (root->data == key) {
return true;
}
// Search both subtrees since the BST property is not guaranteed
return searchInBinaryTree(root->left, key) || searchInBinaryTree(root->right, key);
}
void mirror(Node* &root)
{
if (root == NULL)
{
return;
}
// Swap left and right subtrees
swap(root->left, root->right);
// Recursively mirror the left and right subtrees
mirror(root->left);
mirror(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 before mirroring-\n";
traversal(root);
cout << endl;
cout << "Height of the tree is " << height(root) << endl;
cout << "Minimum value in the BST is " << minimum(root) << endl;
// Mirror the tree
mirror(root);
cout << "Displaying the elements of the BST after mirroring-\n";
traversal(root);
cout << endl;
int key;
cout << "Enter the data value to be searched in the BST-\n";
cin >> key;
if (searchInBinaryTree(root, key)) {
cout << "Key is present in the BST!" << endl;
} else {
cout << "Key is not present in the BST!" << endl;
}
return 0;
}