-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path10.3.cpp
More file actions
127 lines (124 loc) · 2.64 KB
/
10.3.cpp
File metadata and controls
127 lines (124 loc) · 2.64 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
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
#include<iostream>
using namespace std;
struct node {
int data;
struct node *left;
struct node *right;
};
struct node *start = NULL;
int insert(int data);
void inorder(struct node *temp);
int search(int data);
int main(){
int data,i,n,c=-1,r;
cout<<"enter the no. of elements"<<endl;
cin>>n;
cout<<"enter the elements"<<endl;
for(i=0;i<n;i++){
cin>>data;
insert(data);
}
while(c!=0){
cout<<"0.Exit\n1.Inserting\n2.Searching\n3.Display\nenter your choice"<<endl;
cin>>c;
if(c==1){
cout<<"enter the data"<<endl;
cin>>data;
insert(data);
}
else if(c==2){
cout<<"enter the search element :"<<endl;
cin>>data;
r=search(data);
if(r==-1)
cout<<"search element "<<data<<" is not in the tree"<<endl;
else
cout<<"search element "<<data<<" is present in the tree at a depth of "<<r<<endl;
}
else if(c==3){
cout<<"In order : ";
inorder(start);
cout<<endl;
}
else if(c!=0)
cout<<"enter correct input"<<endl;
}
free(start);
return 0;
}
int insert(int data)
{
struct node *temp,*t;
t = (struct node*)malloc(sizeof(struct node));
t->data = data;
t->right = NULL;
t->left = NULL;
if(start == NULL)
{
start=t;
return 0;
}
temp = start;
for(;;){
if(t->data<temp->data)
{
if(temp->left == NULL)
{
temp->left = t;
return 0 ;
}
else
{
temp = temp->left;
}
}
else
{
if(temp->right == NULL)
{
temp->right = t;
return 0;
}
else
{
temp = temp->right;
}
}
}
}
void inorder(struct node *temp)
{
if(temp->left!=NULL)
inorder(temp->left);
cout<<temp->data<<" ";
if(temp->right!=NULL)
inorder(temp->right);
}
int search(int data){
int d=0;
struct node *temp;
temp = start;
for(;;)
{
if(data>temp->data)
{
if(temp->right==NULL&&temp->left==NULL)
return -1;
else
temp = temp->right;
d++;
}
else if(data<temp->data)
{
if(temp->right==NULL&&temp->left==NULL)
return -1;
else
temp = temp->left;
d++;
}
else if(data==temp->data)
return d;
else
return -1;
}
}