-
Notifications
You must be signed in to change notification settings - Fork 174
/
Copy pathBST.cpp
144 lines (126 loc) · 2.27 KB
/
BST.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
143
144
#include <bits/stdc++.h>
using namespace std;
#define IOS \
ios::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0);
#define PB push_back
typedef long long ll;
#define endl "\n"
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;
// 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 << ", ";
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;
}