-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST.c
151 lines (127 loc) · 2.95 KB
/
BST.c
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
#include <stdio.h>
#include <malloc.h>
struct node
{
int data;
struct node *left, *right;
};
struct node *root = NULL;
int options()
{
int choice;
printf("\n1.Insert Node\t2.Delete Node\t3.Display\t4.Exit\nEnter the choice: ");
scanf("%d", &choice);
return choice;
}
struct node *create()
{
struct node *newnode;
newnode = (struct node *)(malloc(sizeof(struct node)));
int number;
printf("Enter the data to be inserted : ");
scanf("%d", &number);
newnode->data = number;
newnode->left = NULL;
newnode->right = NULL;
return newnode;
}
struct node *insert(struct node *root, struct node *newnode)
{
if (root == NULL)
{
return newnode;
}
if (newnode->data < root->data)
{
root->left = insert(root->left, newnode);
}
if (newnode->data > root->data)
{
root->right = insert(root->right, newnode);
}
return root;
}
struct node *minValue(struct node *root)
{
if (root->left == NULL)
{
return root;
}
else
{
return minValue(root->left);
}
}
struct node *deleteNode(struct node *root, int key)
{
if (root == NULL)
return root;
if (key < root->data)
root->left = deleteNode(root->left, key);
else if (key > root->data)
root->right = deleteNode(root->right, key);
// root to be deleted
else
{
// node with only one child or no child
if (root->left == NULL)
{
struct node *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
struct node *temp = root->left;
free(root);
return temp;
}
// node with two children inorder successor
struct node *temp = minValue(root->right);
// Copy the data
root->data = temp->data;
// Delete the inorder successor
root->right = deleteNode(root->right, temp->data);
}
return root;
}
void display(struct node *starter) // this is inorder traversal
{
if (root == NULL)
{
printf("Tree is EMpty\n");
return;
}
if (starter != NULL)
{
display(starter->left);
printf("%d ", starter->data);
display(starter->right);
}
}
int main()
{
printf("Welcome to binary tree DS Operations\n");
int key;
do
{
switch (options())
{
case 1:
root = insert(root, create());
break;
case 2:
printf("Enter the value to delete : ");
scanf("%d", &key);
root = deleteNode(root, key);
break;
case 3:
display(root);
break;
case 4:
exit(0);
break;
}
} while (1);
return 0;
}