-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bst.c
126 lines (98 loc) · 2.18 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
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node* left;
struct Node* right;
}Node;
void insert(Node** root,int item){
if(*root == NULL)
{
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = item;
new_node->left = NULL;
new_node->right = NULL;
*root = new_node;
return;
}
if((*root)->data < item)
insert(&(*root)->right,item);
else
insert(&(*root)->left,item);
}
Node* succ(Node* root)
{
while(root->left != NULL) root = root->left;
return root;
}
Node* Delete(Node *root, int data) {
if(root == NULL){
printf("Node %d is not found in the tree",data);
exit(0);
}
else if(data < root->data) root->left = Delete(root->left,data);
else if (data > root->data) root->right = Delete(root->right,data);
else {
if(root->left == NULL && root->right == NULL) {
free(root);
root = NULL;
}
else if(root->left == NULL) {
Node *temp = root;
root = root->right;
free(temp);
}
else if(root->right == NULL) {
Node *temp = root;
root = root->left;
free(temp);
}
else {
struct Node *temp = succ(root->right);
root->data = temp->data;
root->right = Delete(temp,temp->data);
}
}
return root;
}
void inOrder(Node* root)
{
if(root == NULL)
return;
inOrder(root->left);
printf("%d ",root->data);
inOrder(root->right);
}
void preOrder(Node* root)
{
if(root == NULL)
return;
printf("%d ",root->data);
preOrder(root->left);
preOrder(root->right);
}
int main()
{
int N=0,a;
Node* root=NULL;
scanf("%d",&N);
for(int i=0;i<N;i++)
{
scanf("%d",&a);
insert(&root,a);
}
scanf("%d",&N);
for(int i=0;i<N;i++)
{
if(root == NULL)
{
printf("root is null");
break;
}
scanf("%d",&a);
root = Delete(root,a);
}
inOrder(root);
printf("\n");
preOrder(root);
}