-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST(48).cpp
169 lines (147 loc) · 2.17 KB
/
BST(48).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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#include<iostream>
#include<conio.h>
using namespace std;
class node
{
public:
int data;
node *left;
node *right;
}*start;
class tree
{
public:
tree() //consturctor
{
start = NULL;
}
node *create_node(int value)
{
node *t = new node();
t->data = value;
t->left = NULL;
t->right = NULL;
return t;
}
void insert_tree(node *temp,int val)
{
node *p;
if(start==NULL)
{
temp= create_node(val);
start = temp;
return ;
}
temp = start;
while(temp!=NULL) {
if(val<temp->data)
{
p = temp;
temp = temp->left;
}
else
{
p =temp;
temp = temp->right;
}
}
if(p->data < val)
{
p->right = create_node(val);
}
else
{
p->left = create_node(val);
}
return ;
}
void inorder(node *start)
{
if(start ==NULL)
{
return;
}
cout<<start->data<<" ";
inorder(start->left);
inorder(start->right);
}
void search()
{
node *t = start;
node *p =NULL; //p pointer keep parent node
cout<<"\nenter searching key ";
int key;
cin>>key;
while(t!=NULL && t->data!=key)
{
p=t; //where p is moving behind the t (current place) therefore p remains at parent node always
if(key<t->data)
{
t=t->left;
}
else
{
t=t->right;
}
if(t==NULL)
{
cout<<"\n key not found ";
return ;
}
if( p==NULL)
{
cout<<" \nfound at root node \n";
}
else
{
if(key<p->data)
{
cout<<" given key smaller than root is in left node "<<p->data; //given key is smaller than root node so it can be in left
}
else
{
cout<<" given key is in right node "<<p->data; // opposite of above
}
}
}
}
};
int main()
{ int num,ch;
tree sl;
while(1)
{
cout<<"\nenter choice :";
cout<<"\n1. insertion\t\t\t\t2. searching\n";
cout<<"\n3.traverse(inorder)\t\t\t4.Exit\n";
cin>>ch;
switch(ch)
{
case 1:
{
cout<<"\nenter value in tree\n";
cin>>num;
sl.insert_tree(start,num);
break;
}
case 2:
{
sl.search();
break;
}
case 3:
{
sl.inorder(start);
break;
}
case 4:
{
return 0;
}
default:
{
cout<<"\nwrong choice...";
}
}
}
}