forked from akshitagupta15june/100code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search_tree.c
More file actions
136 lines (125 loc) · 2.24 KB
/
Copy pathbinary_search_tree.c
File metadata and controls
136 lines (125 loc) · 2.24 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
128
129
130
131
132
133
134
135
136
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *root=NULL;
struct node *temp;
struct node *create();
struct node *insertion(struct node *temp,struct node *root);
struct node *deletion(struct node *root,int data);
struct node *inorder_succesor(struct node *root);
struct node *display(struct node *root);
struct node *create()
{
struct node *new;
printf("\nEnter the data of new node\t");
new=(struct node*)malloc(sizeof(struct node));
scanf("%d",&new->data);
new->left=new->right=NULL;
return new;
}
struct node *insertion(struct node *temp,struct node *root)
{
if(temp->data<root->data)
{
if(root->left!=NULL)
insertion(temp,root->left);
else
root->left=temp;
}
if(temp->data>root->data)
{
if(root->right!=NULL)
insertion(temp,root->right);
else
root->right=temp;
}
}
struct node *display(struct node *root)
{
if(root!=NULL)
{
printf("%d ",root->data);
display(root->left);
display(root->right);
}
}
struct node *deletion(struct node *root,int data)
{
if(root==NULL)
{
return root;
}
//no child
else if(root->left==NULL && root->right==NULL)
{
free(root);
root=NULL;
}
else if(data<root->data)
{
root->left=deletion(root->left,data);
}
else if(data>root->data)
{
root->right=deletion(root->right,data);
}
else
{
//one child
if(root->left==NULL)
{
struct node *temp=root;
root=root->right;
free(temp);
}
else if(root->right==NULL)
{
struct node *temp=root;
root=root->left;
free(temp);
}
else
{
temp=inorder_succesor(root->right);
root->data=temp->data;
root->right=deletion(root->right,temp->data);
}
}
return root;
}
struct node *inorder_succesor(struct node *root)
{
while(root->left!=NULL)
{
root=root->left;
return root;
}
}
int main()
{
char ch;
int dat;
do
{
temp=create();
if(root==NULL)
root=temp;
else
insertion(temp,root);
printf("\nDo you want to enter more(y/n)?");
getchar();
scanf("%c",&ch);
}while(ch=='y'|ch=='Y');
display(root);
printf("Enter data you want to delete\t");
scanf("%d",&dat);
root=deletion(root,dat);
printf("Elements after deletion \t");
display(root);
return 0;
}