# The source code
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 |
#include <stdio.h>
#include <stdlib.h>
// 이해하자! 어렵다! cursive algorithm
struct node
{
int i;
struct node * left;
struct node * right;
};
struct node * root = 0;
void addToBST(int n)
{
struct node * cur = (struct node *)malloc(sizeof(struct node));
cur->left = 0;
cur->right = 0;
cur->i = n;
if (root == 0)
{
root = cur;
}
else
{
struct node * temp = root;
while (1)
{
if (temp->i >= cur->i) //left
{
if (temp->left == 0)
{
temp->left = cur;
return;
}
else
{
temp = temp->left;
}
}
else //right
{
if (temp->right == 0)
{
temp->right = cur;
return;
}
else
{
temp = temp->right;
}
}
}
}
}
struct node * findLeast(struct node * node)
{
struct node * cur = node;
while (cur->left != 0)
{
cur = cur->left;
}
return cur;
}
struct node * removeNode(struct node * node, int key)
{
if (node == 0)
{
return 0;
}
if (key == node->i)
{
if (node->left == 0 && node->right == 0)
{
free(node);
return 0;
}
else if (node->left == 0) // 오른쪽 자식만 있는 경우
{
struct node * ret = node->right;
free(node);
return ret;
}
else if (node->right == 0) // 왼쪽 자식만 있는 경우
{
struct node * ret = node->left;
free(node);
return ret;
}
else // 두쪽다 자식이 있는 경우
{
struct node * toReplace = findLeast(node->right);
node->i = toReplace->i;
node->right = removeNode(node->right, toReplace->i);
return node;
}
}
else if (key < node->i)
{
node->left = removeNode(node->left, key);
return node;
}
else
{
node->right = removeNode(node->right, key);
return node;
}
}
void printBST(struct node * node)
{
if (node == 0)
{
return;
}
printBST(node->left);
printf("%d -> ", node->i);
printBST(node->right);
}
void main()
{
addToBST(10);
addToBST(5);
addToBST(20);
addToBST(30);
addToBST(7);
addToBST(40);
addToBST(3);
addToBST(33);
printBST(root);
printf("\n");
removeNode(root, 30);
printf("BST after removing root 30 : ");
printBST(root);
printf("\n");
} |
cs |
# The result
'그 외 공부 > Algorithm' 카테고리의 다른 글
# 9_Heap (0) | 2017.11.05 |
---|---|
# 8_Contacts with BST (0) | 2017.11.05 |
# 6_String Queue (0) | 2017.11.05 |
# 5_CircularQueue (0) | 2017.11.05 |
# 4_Post calculation with stack (0) | 2017.11.05 |