-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplement Binary Search Tree..cpp
70 lines (60 loc) · 1.31 KB
/
implement 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
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
Node(int data) {
this->data = data;
left = right = nullptr;
}
};
class BST {
public:
Node *root;
BST() { root = nullptr; }
void insert(int data) { root = insertNode(root, data); }
Node *insertNode(Node *node, int data) {
if (node == nullptr) {
return new Node(data);
}
if (data < node->data) {
node->left = insertNode(node->left, data);
} else if (data > node->data) {
node->right = insertNode(node->right, data);
}
return node;
}
bool find(int data) { return findNode(root, data); }
bool findNode(Node *node, int data) {
if (node == nullptr) {
return false;
}
if (data == node->data) {
return true;
}
if (data < node->data) {
return findNode(node->left, data);
} else {
return findNode(node->right, data);
}
}
};
int main() {
BST bst;
bst.insert(5);
bst.insert(3);
bst.insert(2);
bst.insert(4);
bst.insert(7);
bst.insert(6);
bst.insert(8);
int num = 2;
if (bst.find(num)) {
cout << num << " is found in the tree." << endl;
} else {
cout << num << " is not found in the tree." << endl;
}
return 0;
}