4
* \brief binary search tree
6
* Generic balanced binary search tree (Red Black Tree) implementation
8
* (C) 2009 by the GRASS Development Team
10
* This program is free software under the GNU General Public License
11
* (>=v2). Read the file COPYING that comes with GRASS for details.
13
* \author Original author Julienne Walker 2003, 2008
14
* GRASS implementation Markus Metz, 2009
17
/* balanced binary search tree implementation
19
* this one is a Red Black Tree, no parent pointers, no threads
20
* The core code comes from Julienne Walker's tutorials on binary search trees
21
* original license: public domain
22
* http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_rbtree.aspx
23
* some ideas come from libavl (GPL >= 2)
25
* Red Black Trees are used to maintain a data structure with
26
* search, insertion and deletion in O(log N) time
35
#include <grass/gis.h>
36
#include <grass/glocale.h>
40
/* internal functions */
41
struct RB_NODE *rbtree_single(struct RB_NODE *, int);
42
struct RB_NODE *rbtree_double(struct RB_NODE *, int);
43
void *rbtree_first(struct RB_TRAV *);
44
void *rbtree_next(struct RB_TRAV *);
45
struct RB_NODE *rbtree_make_node(size_t, void *);
46
int is_red(struct RB_NODE *);
49
/* create new tree and initialize
50
* returns pointer to new tree, NULL for memory allocation error
52
struct RB_TREE *rbtree_create(rb_compare_fn *compare, size_t rb_datasize)
54
struct RB_TREE *tree = (struct RB_TREE *)malloc(sizeof(struct RB_TREE));
57
G_warning("RB tree: Out of memory!");
63
tree->datasize = rb_datasize;
64
tree->rb_compare = compare;
71
/* add an item to a tree
72
* non-recursive top-down insertion
73
* the algorithm does not allow duplicates and also does not warn about a duplicate
74
* returns 1 on success, 0 on failure
76
int rbtree_insert(struct RB_TREE *tree, void *data)
80
if (tree->root == NULL) {
81
/* create a new root node for tree */
82
tree->root = rbtree_make_node(tree->datasize, data);
83
if (tree->root == NULL)
87
struct RB_NODE head = { 0 }; /* False tree root */
88
struct RB_NODE *g, *t; /* Grandparent & parent */
89
struct RB_NODE *p, *q; /* Iterator & parent */
90
int dir = 0, last = 0;
95
q = t->link[1] = tree->root;
97
/* Search down the tree */
100
/* Insert new node at the bottom */
101
p->link[dir] = q = rbtree_make_node(tree->datasize, data);
105
else if (is_red(q->link[0]) && is_red(q->link[1])) {
112
/* Fix red violation */
113
if (is_red(q) && is_red(p)) {
114
int dir2 = t->link[1] == g;
116
if (q == p->link[last])
117
t->link[dir2] = rbtree_single(g, !last);
119
t->link[dir2] = rbtree_double(g, !last);
123
dir = tree->rb_compare(q->data, data);
125
/* Stop if found. This check also disallows duplicates in the tree */
131
/* Move the helpers down */
140
tree->root = head.link[1];
143
/* Make root black */
151
/* remove an item from a tree that matches given data
152
* non-recursive top-down removal
153
* returns 1 on successful removal
154
* returns 0 if data item was not found
156
int rbtree_remove(struct RB_TREE *tree, const void *data)
158
struct RB_NODE head = { 0 }; /* False tree root */
159
struct RB_NODE *q, *p, *g; /* Helpers */
160
struct RB_NODE *f = NULL; /* Found item */
161
int dir = 1, removed = 0;
163
assert(tree && data);
165
if (tree->root == NULL) {
166
return 0; /* empty tree, nothing to remove */
172
q->link[1] = tree->root;
174
/* Search and push a red down */
175
while (q->link[dir] != NULL) {
181
dir = tree->rb_compare(q->data, data);
183
/* Save found node */
189
/* Push the red node down */
190
if (!is_red(q) && !is_red(q->link[dir])) {
191
if (is_red(q->link[!dir]))
192
p = p->link[last] = rbtree_single(q, dir);
193
else if (!is_red(q->link[!dir])) {
194
struct RB_NODE *s = p->link[!last];
197
if (!is_red(s->link[!last]) && !is_red(s->link[last])) {
204
int dir2 = g->link[1] == p;
206
if (is_red(s->link[last]))
207
g->link[dir2] = rbtree_double(p, last);
208
else if (is_red(s->link[!last]))
209
g->link[dir2] = rbtree_single(p, last);
211
/* Ensure correct coloring */
212
q->red = g->link[dir2]->red = 1;
213
g->link[dir2]->link[0]->red = 0;
214
g->link[dir2]->link[1]->red = 0;
221
/* Replace and remove if found */
225
p->link[p->link[1] == q] = q->link[q->link[0] == NULL];
232
G_debug(2, "RB tree: data not found in search tree");
234
/* Update root and make it black */
235
tree->root = head.link[1];
236
if (tree->root != NULL)
242
/* find data item in tree
243
* returns pointer to data item if found else NULL
245
void *rbtree_find(struct RB_TREE *tree, const void *data)
247
struct RB_NODE *curr_node = tree->root;
250
assert(tree && data);
252
while (curr_node != NULL) {
253
cmp = tree->rb_compare(curr_node->data, data);
255
return curr_node->data; /* found */
257
curr_node = curr_node->link[cmp < 0];
262
/* initialize tree traversal
263
* (re-)sets trav structure
266
int rbtree_init_trav(struct RB_TRAV *trav, struct RB_TREE *tree)
268
assert(trav && tree);
271
trav->curr_node = tree->root;
278
/* traverse the tree in ascending order
279
* useful to get all items in the tree non-recursively
280
* struct RB_TRAV *trav needs to be initialized first
281
* returns pointer to data, NULL when finished
283
void *rbtree_traverse(struct RB_TRAV *trav)
287
if (trav->curr_node == NULL) {
289
G_debug(1, "RB tree: empty tree");
291
G_debug(1, "RB tree: finished traversing");
297
return rbtree_next(trav);
300
return rbtree_first(trav);
304
/* find start point to traverse the tree in ascending order
305
* useful to get a selection of items in the tree
306
* magnitudes faster than traversing the whole tree
307
* may return first item that's smaller or first item that's larger
308
* struct RB_TRAV *trav needs to be initialized first
309
* returns pointer to data, NULL when finished
311
void *rbtree_traverse_start(struct RB_TRAV *trav, const void *data)
315
assert(trav && data);
317
if (trav->curr_node == NULL) {
319
G_warning("RB tree: empty tree");
321
G_warning("RB tree: finished traversing");
327
return rbtree_next(trav);
329
/* else first time, get start node */
334
while (trav->curr_node != NULL) {
335
dir = trav->tree->rb_compare(trav->curr_node->data, data);
336
/* exact match, great! */
338
return trav->curr_node->data;
341
/* end of branch, also reached if
342
* smallest item is larger than search template or
343
* largest item is smaller than search template */
344
if (trav->curr_node->link[dir] == NULL)
345
return trav->curr_node->data;
347
trav->up[trav->top++] = trav->curr_node;
348
trav->curr_node = trav->curr_node->link[dir];
352
return NULL; /* should not happen */
355
/* two functions needed to fully traverse the tree: initialize and continue
356
* useful to get all items in the tree non-recursively
357
* this one here uses a stack
358
* parent pointers or threads would also be possible
359
* but these would need to be added to RB_NODE
360
* -> more memory needed for standard operations
363
/* start traversing the tree
364
* returns pointer to smallest data item
366
void *rbtree_first(struct RB_TRAV *trav)
368
/* get smallest item */
369
while (trav->curr_node->link[0] != NULL) {
370
trav->up[trav->top++] = trav->curr_node;
371
trav->curr_node = trav->curr_node->link[0];
374
return trav->curr_node->data; /* return smallest item */
377
/* continue traversing the tree in ascending order
378
* returns pointer to data item, NULL when finished
380
void *rbtree_next(struct RB_TRAV *trav)
382
if (trav->curr_node->link[1] != NULL) {
383
/* something on the right side: larger item */
384
trav->up[trav->top++] = trav->curr_node;
385
trav->curr_node = trav->curr_node->link[1];
387
/* go down, find smallest item in this branch */
388
while (trav->curr_node->link[0] != NULL) {
389
trav->up[trav->top++] = trav->curr_node;
390
trav->curr_node = trav->curr_node->link[0];
394
/* at smallest item in this branch, go back up */
395
struct RB_NODE *last;
398
if (trav->top == 0) {
399
trav->curr_node = NULL;
402
last = trav->curr_node;
403
trav->curr_node = trav->up[--trav->top];
404
} while (last == trav->curr_node->link[1]);
407
if (trav->curr_node != NULL) {
408
return trav->curr_node->data;
411
return NULL; /* finished traversing */
414
/* destroy the tree */
415
void rbtree_destroy(struct RB_TREE *tree)
418
struct RB_NODE *save = tree->root;
421
Rotate away the left links so that
422
we can treat this like the destruction
425
while((it = save) != NULL) {
426
if (it->link[0] == NULL) {
427
/* No left links, just kill the node and move on */
435
/* Rotate away the left link and check again */
437
it->link[0] = save->link[1];
445
/* used for debugging: check for errors in tree structure */
446
int rbtree_debug(struct RB_TREE *tree, struct RB_NODE *root)
453
struct RB_NODE *ln = root->link[0];
454
struct RB_NODE *rn = root->link[1];
455
int lcmp = 0, rcmp = 0;
457
/* Consecutive red links */
459
if (is_red(ln) || is_red(rn)) {
460
G_warning("Red Black Tree debugging: Red violation");
465
lh = rbtree_debug(tree, ln);
466
rh = rbtree_debug(tree, rn);
469
lcmp = tree->rb_compare(ln->data, root->data);
473
rcmp = tree->rb_compare(rn->data, root->data);
476
/* Invalid binary search tree:
477
* left node >= parent or right node <= parent */
478
if ((ln != NULL && lcmp > -1)
479
|| (rn != NULL && rcmp < 1)) {
480
G_warning("Red Black Tree debugging: Binary tree violation");
484
/* Black height mismatch */
485
if (lh != 0 && rh != 0 && lh != rh) {
486
G_warning("Red Black Tree debugging: Black violation");
490
/* Only count black links */
491
if (lh != 0 && rh != 0)
492
return is_red(root) ? lh : lh + 1;
498
/*******************************************************
500
* internal functions for Red Black Tree maintenance *
502
*******************************************************/
504
/* add a new node to the tree */
505
struct RB_NODE *rbtree_make_node(size_t datasize, void *data)
507
struct RB_NODE *new_node = (struct RB_NODE *)malloc(sizeof(*new_node));
509
if (new_node == NULL)
510
G_fatal_error("RB Search Tree: Out of memory!");
512
new_node->data = malloc(datasize);
513
if (new_node->data == NULL)
514
G_fatal_error("RB Search Tree: Out of memory!");
516
memcpy(new_node->data, data, datasize);
517
new_node->red = 1; /* 1 is red, 0 is black */
518
new_node->link[0] = NULL;
519
new_node->link[1] = NULL;
524
/* check for red violation */
525
int is_red(struct RB_NODE *root)
528
return root->red == 1;
533
/* single rotation */
534
struct RB_NODE *rbtree_single(struct RB_NODE *root, int dir)
536
struct RB_NODE *newroot = root->link[!dir];
538
root->link[!dir] = newroot->link[dir];
539
newroot->link[dir] = root;
547
/* double rotation */
548
struct RB_NODE *rbtree_double(struct RB_NODE *root, int dir)
550
root->link[!dir] = rbtree_single(root->link[!dir], !dir);
551
return rbtree_single(root, dir);