-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST.c
160 lines (142 loc) · 2.78 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
152
153
154
155
156
157
158
159
#include<stdio.h>
#include<stdlib.h>
typedef struct {
int key;
} TItem;
typedef struct Node* BST;
typedef struct Node {
TItem Item;
BST left, right;
} Node;
BST BST_search(BST No, int x);
int BST_insert(BST *pRaiz, TItem x);
int BST_remove(BST *pRaiz, int x);
void BST_predecessor(BST *q, BST *r);
void BST_sucessor(BST *q, BST *r);
BST BST_create();
BST BST_createNode(TItem x, BST left, BST right);
void preOrder(BST No);
int main()
{
int n,i;
TItem k;
int search;
BST raiz;
raiz = BST_create();
scanf("%d", &n);
scanf("%d", &k);
raiz = BST_createNode(k, NULL, NULL);
for(i=0; i<n-1; i++)
{
scanf("%d", &k);
BST_insert(&raiz, k);
}
scanf("%d", &search);
if(BST_remove(&raiz, search)==1) preOrder(raiz);
else{
k.key = search;
BST_insert(&raiz, k);
preOrder(raiz);
}
return 0;
}
BST BST_create()
{
return NULL;
}
BST BST_createNode(TItem x, BST left, BST right)
{
BST No;
No = (BST) malloc(sizeof(Node));
No->Item = x;
No->left = left;
No->right = right;
return No;
}
BST BST_search(BST root, int x)
{
BST No;
No = root;
while ((No != NULL) && (x != No->Item.key))
{
if (x < No->Item.key) No = No->left;
else if (x > No->Item.key) No = No->right;
}
return No;
}
int BST_insert(BST *pr, TItem x)
{
BST *pNo;
pNo = pr;
while ((*pNo != NULL) && (x.key != (*pNo)->Item.key))
{
if (x.key < (*pNo)->Item.key) pNo = &(*pNo)->left;
else if (x.key > (*pNo)->Item.key) pNo = &(*pNo)->right;
}
if (*pNo == NULL)
{
*pNo = BST_createNode(x, BST_create(), BST_create());
return 1;
}
return 0;
}
int BST_remove(BST *pr, int x)
{
BST *p, q;
p = pr;
while ((*p != NULL) && (x != (*p)->Item.key))
{
if (x < (*p)->Item.key) p = &(*p)->left;
else if (x > (*p)->Item.key) p = &(*p)->right;
}
if (*p != NULL)
{
q = *p;
if (q->left == NULL){
*p = q->right;
return 1;
}
else if (q->right == NULL){
*p = q->left;
return 1;
}
else
{
BST_sucessor(&q, &q->right);
free(q);
return 1;
}
}
return 0;
}
void BST_predecessor(BST *q, BST *r)
{
if ((*r)->right != NULL) BST_predecessor(q, &(*r)->right);
else
{
(*q)->Item = (*r)->Item;
*q = *r;
*r = (*r)->left;
}
}
void BST_sucessor(BST *q, BST *r)
{
if ((*r)->left != NULL) BST_sucessor(q, &(*r)->left);
else
{
(*q)->Item = (*r)->Item;
*q = *r;
*r = (*r)->right;
}
}
void preOrder(BST No)
{
if (No != NULL)
{
printf("(%d",No->Item.key);
preOrder(No->left);
preOrder(No->right);
printf(")");
}
else printf("()");
}