-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearchTree.cpp
More file actions
123 lines (101 loc) · 2.74 KB
/
binarySearchTree.cpp
File metadata and controls
123 lines (101 loc) · 2.74 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
#include <iostream>
using namespace std;
struct Node {
struct Node* right;
int data;
struct Node* left;
};
struct Node* createNode(int value) {
struct Node* newNode = new Node;
newNode->data = value;
newNode->left = nullptr;
newNode->right = nullptr;
return newNode;
}
void insertNode(struct Node** root, int value) {
if (*root == nullptr) {
*root = createNode(value);
}
else if ((*root)->data > value) {
insertNode(&(*root)->left, value);
}
else {
insertNode(&(*root)->right, value);
}
}
string searchTree(struct Node* root, struct Node** resultNode) {
if (root == nullptr) {
return "Empty tree.";
}
else {
int key;
cout << "Enter the key : ";
cin >> key;
string path = "root";
while (root != nullptr) {
if (root->data == key) {
*resultNode = root;
return path;
}
else if (root->data > key) {
path += "->left";
root = root->left;
}
else {
path += "->right";
root = root->right;
}
}
return "Not found in tree.";
}
}
void mainMenu() {
cout << "\nChoose : ";
cout << "\n[1] Insert Node";
cout << "\n[2] Search tree";
cout << "\n[3] Exit";
cout << "\nChoose option : ";
}
int main() {
int option, size;
struct Node* root = nullptr;
do
{
mainMenu();
cin >> option;
switch (option) {
case 1: {
cout << "Enter the number of elments : ";
cin >> size;
int data[size];
for (int i = 0; i < size; i++) {
cout << "Enter the element #" << (i + 1) << " : ";
cin >> data[i];
insertNode(&root, data[i]);
}
break;
}
case 2: {
struct Node* resultNode = nullptr;
string path = searchTree(root, &resultNode);
if (resultNode != nullptr) {
cout << "Output : [" << resultNode->data << ", "
<< (resultNode->left == nullptr ? "NULL" : to_string(resultNode->left->data)) << ", "
<< (resultNode->right == nullptr ? "NULL" : to_string(resultNode->right->data)) << "]"
<< endl;
cout << "Path : " << path << endl;
}
else {
cout << "Output : Node not found." << endl;
}
break;
}
case 3: {
cout << "\nExiting...\n" << endl;
break;
}
default: cout << "Choose a correct option." << endl;
}
} while (option != 3);
return 0;
}