-
Notifications
You must be signed in to change notification settings - Fork 255
/
Copy path02 BST Insert,Inorder&Search.cpp
117 lines (98 loc) · 1.98 KB
/
02 BST Insert,Inorder&Search.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
#include <iostream>
using namespace std;
class Node {
public:
Node* lchild;
int data;
Node* rchild;
};
class BST {
private:
Node* root;
public:
BST() { root = nullptr; }
Node* getRoot() { return root; }
void Insert(int key);
void Inorder(Node* p);
Node* Search(int key);
};
void BST::Insert(int key) {
Node* t = root;
Node* p;
Node* r=t;
// root is empty
if (root == nullptr) {
p = new Node;
p->data = key;
p->lchild = nullptr;
p->rchild = nullptr;
root = p;
return;
}
while (t != nullptr) {
r = t;
if (key < t->data) {
t = t->lchild;
}
else if (key > t->data) {
t = t->rchild;
}
else {
return;
}
}
// Now t points at NULL and r points at insert location
p = new Node;
p->data = key;
p->lchild = nullptr;
p->rchild = nullptr;
if (key < r->data) {
r->lchild = p;
}
else {
r->rchild = p;
}
}
void BST::Inorder(Node* p) {
if (p) {
Inorder(p->lchild);
cout << p->data << ", " << flush;
Inorder(p->rchild);
}
}
Node* BST::Search(int key) {
Node* t = root;
while (t != nullptr) {
if (key == t->data) {
return t;
}
else if (key < t->data) {
t = t->lchild;
}
else {
t = t->rchild;
}
}
return nullptr;
}
int main() {
BST bst;
// Insert
bst.Insert(10);
bst.Insert(5);
bst.Insert(20);
bst.Insert(8);
bst.Insert(30);
// Inorder traversal
bst.Inorder(bst.getRoot());
cout << endl;
// Search
Node* temp = bst.Search(2);
if (temp != nullptr) {
cout << temp->data << endl;
}
else {
cout << "Element not found" << endl;
}
return 0;
}