2-3 Tree
- 모든 리프가 같은 깊이에 있는 다진 탐색 트리
2-3 트리 (2-3 Tree)
2-3 트리는 모든 리프가 같은 깊이에 있는 탐색 트리이다. 한 노드에 정렬된 키를 한 개 또는 두 개 둔다. 내부 노드에 키가 한 개면 자식이 두 개, 키가 두 개면 자식이 세 개다. 리프는 같은 수의 키를 보관하지만 자식은 없다.
| 노드 | 저장된 키 | 내부 노드에서 각 자식이 담당하는 범위 |
|---|---|---|
| 2-노드 | $a$ | 왼쪽 $x < a$, 오른쪽 $x > a$ |
| 3-노드 | $a < b$ | 왼쪽 $x < a$, 가운데 $a < x < b$, 오른쪽 $x > b$ |
이진 탐색 트리에서는 한 키가 두 범위를 나눈다. 2-3 트리의 3-노드에서는 두 키가 세 범위를 나눈다. 이러한 다진 탐색 구조는 최대 세 자식을 가진 B 트리의 한 형태로 볼 수 있다.
구현 방법
1. 탐색
노드에 저장된 키를 작은 것부터 비교한다. 같은 키가 있으면 탐색을 끝낸다. 첫 번째로 만난 더 큰 키가 배열의 $i$번째 키라면, 찾는 값은 그 키 바로 앞 범위에 있으므로 $i$번째 자식으로 이동한다. 모든 키보다 크면 맨 오른쪽 자식으로 간다. 비어 있는 자식까지 내려가면 키가 없다.
예를 들어 루트가 $[20, 40]$일 때 $30$을 찾으려면 $20 < 30 < 40$이므로 가운데 자식으로 내려간다. $40$을 찾으면 루트에서 바로 끝난다.
2. 삽입
탐색과 같은 방식으로 내려가 기존 키와 일치하면 삽입을 끝낸다. 빈자리를 찾으면 리프에 키를 정렬된 순서로 넣는다.
- 키가 하나였으면 두 키를 보관하는 3-노드가 된다.
- 이미 키가 두 개라면 삽입한 키까지 잠시 세 개가 된다. 가운데 키를 부모로 올리고, 작은 키와 큰 키를 각각 별도의 노드에 둔다. 내부 노드가 분할될 때는 임시 자식 네 개도 순서를 유지하며 양쪽 노드에 두 개씩 나눈다.
- 부모도 가득 차 있으면 같은 분할을 반복한다. 루트가 분할되면 승격된 키를 담는 새 루트가 생긴다. 기존 리프들의 깊이가 모두 한 단계 증가한다.
$10, 20, 30, 40, 50, 60$을 넣은 트리에 $70$을 추가해 보자. 오른쪽 리프 $[50, 60]$가 분할되어 $60$이 부모로 올라간다. 루트는 잠시 $[20, 40, 60]$이 되므로 다시 분할한다. 이번에는 $40$이 새 루트가 되고 $20$과 $60$이 각각 왼쪽과 오른쪽 자식이 된다.
3. 삭제
내부 노드의 키를 지울 때는 그 키 바로 왼쪽 서브트리의 최댓값, 즉 중위 선행자로 대체한다. 이제 리프에 있는 선행자 하나를 삭제하는 문제로 바뀐다. 리프에 키가 남으면 연산이 끝난다. 키가 하나도 없으면 다음 방법으로 복구한다.
- 바로 옆 형제 중 키가 두 개인 노드가 있다면, 부모의 경계 키를 빈 노드로 내리고 형제의 가장 가까운 키를 부모로 올린다. 내부 노드의 부족을 복구할 때는 형제의 경계 자식도 함께 옮긴다.
- 양옆에 빌려줄 형제가 없으면, 빈 노드와 바로 옆 형제를 부모의 경계 키 하나와 합친다. 부모에서 키 하나와 자식 포인터 하나가 줄어든다. 부모까지 비면 같은 복구를 반복한다.
- 루트가 비면 남은 자식이 새 루트가 된다. 자식도 없으면 빈 트리가 된다.
그림 오른쪽의 트리에서 $10$을 삭제하면 형제 $[30]$은 키를 빌려줄 수 없다. 부모의 $20$을 내려 $[20, 30]$으로 합친다. 그 부모도 비므로 이번에는 루트의 $40$과 오른쪽 형제 $[60]$을 합친다. 결과적으로 $[40, 60]$이 새 루트가 되고, 자식은 왼쪽부터 $[20, 30], [50], [70]$이 된다.
소스코드
data와 child 배열에는 분할 직전 상태를 위한 슬롯을 하나 더 둔다. insert_recursive가 승격 키와 새 오른쪽 노드를 반환하면, 부모는 이미 연결된 왼쪽 노드를 그대로 두고 그 오른쪽에 새 노드를 추가한다. delete_recursive는 키가 없는 자식을 발견하면 부모 단계에서 fix_underflow를 호출한다.
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int count;
int data[3];
struct node *child[4];
} node;
typedef struct {
int data;
node *right; // NULL이면 분할하지 않았다.
} Split;
node *create_node(int x) {
node *t = malloc(sizeof *t);
if (t == NULL) {
fputs("Failed to allocate a node.\n", stderr);
exit(EXIT_FAILURE);
}
*t = (node){.count = 1, .data = {x}};
return t;
}
int find_index(const node *t, int x) {
int i = 0;
while (i < t->count && t->data[i] < x) {
++i;
}
return i;
}
bool findCertainNode(const node *root, int x) {
while (root != NULL) {
int i = find_index(root, x);
if (i < root->count && root->data[i] == x) {
return true;
}
root = root->child[i];
}
return false;
}
void insert_at(node *t, int i, int x, node *right) {
for (int j = t->count; j > i; --j) {
t->data[j] = t->data[j - 1];
t->child[j + 1] = t->child[j];
}
t->data[i] = x;
t->child[i + 1] = right;
++t->count;
}
Split insert_recursive(node *t, int x) {
int i = find_index(t, x);
if (i < t->count && t->data[i] == x) {
return (Split){0};
}
if (t->child[0] == NULL) {
insert_at(t, i, x, NULL);
} else {
Split split = insert_recursive(t->child[i], x);
if (split.right == NULL) {
return split;
}
insert_at(t, i, split.data, split.right);
}
if (t->count < 3) {
return (Split){0};
}
node *right = create_node(t->data[2]);
right->child[0] = t->child[2];
right->child[1] = t->child[3];
t->child[2] = NULL;
t->child[3] = NULL;
t->count = 1;
return (Split){t->data[1], right};
}
node *insert(node *root, int x) {
if (root == NULL) {
return create_node(x);
}
Split split = insert_recursive(root, x);
if (split.right == NULL) {
return root;
}
node *new_root = create_node(split.data);
new_root->child[0] = root;
new_root->child[1] = split.right;
return new_root;
}
void remove_separator(node *t, int i) {
for (int j = i; j + 1 < t->count; ++j) {
t->data[j] = t->data[j + 1];
t->child[j + 1] = t->child[j + 2];
}
t->child[t->count] = NULL;
--t->count;
}
void fix_underflow(node *parent, int i) {
node *t = parent->child[i];
node *left = i > 0 ? parent->child[i - 1] : NULL;
node *right = i < parent->count ? parent->child[i + 1] : NULL;
if (left != NULL && left->count == 2) {
t->data[0] = parent->data[i - 1];
t->child[1] = t->child[0];
t->child[0] = left->child[2];
parent->data[i - 1] = left->data[1];
left->child[2] = NULL;
--left->count;
++t->count;
} else if (right != NULL && right->count == 2) {
t->data[0] = parent->data[i];
t->child[1] = right->child[0];
parent->data[i] = right->data[0];
right->data[0] = right->data[1];
right->child[0] = right->child[1];
right->child[1] = right->child[2];
right->child[2] = NULL;
--right->count;
++t->count;
} else if (left != NULL) {
left->data[1] = parent->data[i - 1];
left->child[2] = t->child[0];
++left->count;
free(t);
remove_separator(parent, i - 1);
} else {
t->data[0] = parent->data[i];
t->data[1] = right->data[0];
t->child[1] = right->child[0];
t->child[2] = right->child[1];
t->count = 2;
free(right);
remove_separator(parent, i);
}
}
void delete_recursive(node *t, int x) {
int i = find_index(t, x);
bool found = i < t->count && t->data[i] == x;
if (t->child[0] == NULL) {
if (found) {
remove_separator(t, i);
}
return;
}
if (found) {
const node *prev = t->child[i];
while (prev->child[0] != NULL) {
prev = prev->child[prev->count];
}
x = prev->data[prev->count - 1];
t->data[i] = x;
}
delete_recursive(t->child[i], x);
if (t->child[i]->count == 0) {
fix_underflow(t, i);
}
}
node *delete_node(node *root, int x) {
if (root == NULL) {
return NULL;
}
delete_recursive(root, x);
if (root->count == 0) {
node *new_root = root->child[0];
free(root);
return new_root;
}
return root;
}
void inorder(const node *root) {
if (root == NULL) {
return;
}
for (int i = 0; i < root->count; ++i) {
inorder(root->child[i]);
printf("%d ", root->data[i]);
}
inorder(root->child[root->count]);
}
void free_tree(node *root) {
if (root == NULL) {
return;
}
for (int i = 0; i <= root->count; ++i) {
free_tree(root->child[i]);
}
free(root);
}
int main(void) {
node *root = NULL;
for (int x = 10; x <= 70; x += 10) {
root = insert(root, x);
}
printf("find 60: %d\n", findCertainNode(root, 60));
root = delete_node(root, 10);
inorder(root); // 20 30 40 50 60 70
putchar('\n');
free_tree(root);
return 0;
}
시간 복잡도
모든 리프의 깊이가 같고 각 내부 노드가 자식을 최소 두 개, 최대 세 개 가지므로 키가 $N$개일 때 높이는 $\Theta(\log N)$이다. 각 층에서 비교하는 키는 최대 두 개다. 삽입의 분할과 삭제의 재분배·병합도 방문한 경로를 따라 층마다 상수 시간에 수행한다. 따라서 탐색·삽입·삭제는 $O(\log N)$이다. 트리가 차지하는 공간은 $O(N)$이고 재귀 갱신에는 $O(\log N)$의 추가 호출 스택을 사용한다.
