-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem1.cpp
More file actions
92 lines (71 loc) · 1.9 KB
/
Problem1.cpp
File metadata and controls
92 lines (71 loc) · 1.9 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
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = nullptr;
right = nullptr;
}
};
class BinarySearchTree {
private:
Node* root;
Node* insertRecursive(Node* current, int value) {
if (current == nullptr) {
return new Node(value);
}
if (value < current->data) {
current->left = insertRecursive(current->left, value);
} else if (value > current->data) {
current->right = insertRecursive(current->right, value);
}
return current;
}
public:
BinarySearchTree() {
root = nullptr;
}
void insert(int value) {
root = insertRecursive(root, value);
}
void inOrderTraversal(Node* current) {
if (current != nullptr) {
inOrderTraversal(current->left);
cout << current->data << " ";
inOrderTraversal(current->right);
}
}
bool search(int value, Node* current) {
if (current == nullptr) {
return false;
}
if (value == current->data) {
return true;
} else if (value < current->data) {
return search(value, current->left);
} else {
return search(value, current->right);
}
}
};
int main() {
BinarySearchTree bst;
bst.insert(5);
bst.insert(3);
bst.insert(7);
bst.insert(2);
bst.insert(4);
cout << "In-order Traversal: ";
bst.inOrderTraversal(bst.getRoot());
cout << endl;
int searchValue = 4;
if (bst.search(searchValue, bst.getRoot())) {
cout << searchValue << " found in the BST." << endl;
} else {
cout << searchValue << " not found in the BST." << endl;
}
}