rbtree.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. /*!
  2. * \file rbtree.c
  3. *
  4. * \brief binary search tree
  5. *
  6. * Generic balanced binary search tree (Red Black Tree) implementation
  7. *
  8. * (C) 2009 by the GRASS Development Team
  9. *
  10. * This program is free software under the GNU General Public License
  11. * (>=v2). Read the file COPYING that comes with GRASS for details.
  12. *
  13. * \author Original author Julienne Walker 2003, 2008
  14. * GRASS implementation Markus Metz, 2009
  15. */
  16. /* balanced binary search tree implementation
  17. *
  18. * this one is a Red Black Tree, the bare version, no parent pointers, no threads
  19. * The core code comes from Julienne Walker's tutorials on binary search trees
  20. * original license: public domain
  21. * http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_rbtree.aspx
  22. * some ideas come from libavl (GPL >= 2)
  23. * I could have used some off-the-shelf solution, but that's boring
  24. *
  25. * Red Black Trees are used to maintain a data structure with
  26. * search, insertion and deletion in O(log N) time
  27. */
  28. #include <assert.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <grass/gis.h>
  32. #include <grass/glocale.h>
  33. #include "rbtree.h"
  34. /* internal functions */
  35. void rbtree_destroy2(struct RB_NODE *);
  36. struct RB_NODE *rbtree_single(struct RB_NODE *, int);
  37. struct RB_NODE *rbtree_double(struct RB_NODE *, int);
  38. void *rbtree_first(struct RB_TRAV *);
  39. void *rbtree_next(struct RB_TRAV *);
  40. struct RB_NODE *rbtree_make_node(size_t, void *);
  41. int is_red(struct RB_NODE *);
  42. /* create new tree and initialize
  43. * returns pointer to new tree, NULL for memory allocation error
  44. */
  45. struct RB_TREE *rbtree_create(rb_compare_fn * compare, size_t rb_datasize)
  46. {
  47. struct RB_TREE *tree = G_malloc(sizeof(*tree));
  48. if (tree == NULL) {
  49. G_warning("RB tree: Out of memory!");
  50. return NULL;
  51. }
  52. assert(compare);
  53. tree->datasize = rb_datasize;
  54. tree->rb_compare = compare;
  55. tree->count = 0;
  56. tree->root = NULL;
  57. return tree;
  58. }
  59. /* add an item to a tree
  60. * non-recursive top-down insertion
  61. * the algorithm does not allow duplicates and also does not warn about a duplicate
  62. * returns 1 on success, 0 on failure
  63. */
  64. int rbtree_insert(struct RB_TREE *tree, void *data)
  65. {
  66. assert(tree && data);
  67. if (tree->root == NULL) {
  68. /* create a new root node for tree */
  69. tree->root = rbtree_make_node(tree->datasize, data);
  70. if (tree->root == NULL)
  71. return 0;
  72. }
  73. else {
  74. struct RB_NODE head = { 0 }; /* False tree root */
  75. struct RB_NODE *g, *t; /* Grandparent & parent */
  76. struct RB_NODE *p, *q; /* Iterator & parent */
  77. int dir = 0, last = 0;
  78. /* Set up helpers */
  79. t = &head;
  80. g = p = NULL;
  81. q = t->link[1] = tree->root;
  82. /* Search down the tree */
  83. for (;;) {
  84. if (q == NULL) {
  85. /* Insert new node at the bottom */
  86. p->link[dir] = q = rbtree_make_node(tree->datasize, data);
  87. if (q == NULL)
  88. return 0;
  89. }
  90. else if (is_red(q->link[0]) && is_red(q->link[1])) {
  91. /* Color flip */
  92. q->red = 1;
  93. q->link[0]->red = 0;
  94. q->link[1]->red = 0;
  95. }
  96. /* Fix red violation */
  97. if (is_red(q) && is_red(p)) {
  98. int dir2 = t->link[1] == g;
  99. if (q == p->link[last])
  100. t->link[dir2] = rbtree_single(g, !last);
  101. else
  102. t->link[dir2] = rbtree_double(g, !last);
  103. }
  104. last = dir;
  105. dir = tree->rb_compare(q->data, data);
  106. /* Stop if found. This check also disallows duplicates in the tree */
  107. if (dir == 0)
  108. break;
  109. dir = dir < 0;
  110. /* Move the helpers down */
  111. if (g != NULL)
  112. t = g;
  113. g = p, p = q;
  114. q = q->link[dir];
  115. }
  116. /* Update root */
  117. tree->root = head.link[1];
  118. }
  119. /* Make root black */
  120. tree->root->red = 0;
  121. tree->count++;
  122. return 1;
  123. }
  124. /* remove an item from a tree that matches given data
  125. * non-recursive top-down removal
  126. * returns 1 on successful removal
  127. * returns 0 if data item was not found
  128. */
  129. int rbtree_remove(struct RB_TREE *tree, const void *data)
  130. {
  131. struct RB_NODE head = { 0 }; /* False tree root */
  132. struct RB_NODE *q, *p, *g; /* Helpers */
  133. struct RB_NODE *f = NULL; /* Found item */
  134. int dir = 1, removed = 0;
  135. assert(tree && data);
  136. if (tree->root == NULL) {
  137. return 0; /* empty tree, nothing to remove */
  138. }
  139. /* Set up helpers */
  140. q = &head;
  141. g = p = NULL;
  142. q->link[1] = tree->root;
  143. /* Search and push a red down */
  144. while (q->link[dir] != NULL) {
  145. int last = dir;
  146. /* Update helpers */
  147. g = p, p = q;
  148. q = q->link[dir];
  149. dir = tree->rb_compare(q->data, data);
  150. /* Save found node */
  151. if (dir == 0)
  152. f = q;
  153. dir = dir < 0;
  154. /* Push the red node down */
  155. if (!is_red(q) && !is_red(q->link[dir])) {
  156. if (is_red(q->link[!dir]))
  157. p = p->link[last] = rbtree_single(q, dir);
  158. else if (!is_red(q->link[!dir])) {
  159. struct RB_NODE *s = p->link[!last];
  160. if (s != NULL) {
  161. if (!is_red(s->link[!last]) && !is_red(s->link[last])) {
  162. /* Color flip */
  163. p->red = 0;
  164. s->red = 1;
  165. q->red = 1;
  166. }
  167. else {
  168. int dir2 = g->link[1] == p;
  169. if (is_red(s->link[last]))
  170. g->link[dir2] = rbtree_double(p, last);
  171. else if (is_red(s->link[!last]))
  172. g->link[dir2] = rbtree_single(p, last);
  173. /* Ensure correct coloring */
  174. q->red = g->link[dir2]->red = 1;
  175. g->link[dir2]->link[0]->red = 0;
  176. g->link[dir2]->link[1]->red = 0;
  177. }
  178. }
  179. }
  180. }
  181. }
  182. /* Replace and remove if found */
  183. if (f != NULL) {
  184. G_free(f->data);
  185. f->data = q->data;
  186. p->link[p->link[1] == q] = q->link[q->link[0] == NULL];
  187. G_free(q);
  188. tree->count--;
  189. removed = 1;
  190. }
  191. else
  192. G_debug(2, "RB tree: data not found in search tree");
  193. /* Update root and make it black */
  194. tree->root = head.link[1];
  195. if (tree->root != NULL)
  196. tree->root->red = 0;
  197. return removed;
  198. }
  199. /* find data item in tree
  200. * returns pointer to data item if found else NULL
  201. */
  202. void *rbtree_find(struct RB_TREE *tree, const void *data)
  203. {
  204. struct RB_NODE *curr_node = tree->root;
  205. int cmp;
  206. assert(tree && data);
  207. while (curr_node != NULL) {
  208. cmp = tree->rb_compare(curr_node->data, data);
  209. if (cmp == 0)
  210. return curr_node->data; /* found */
  211. curr_node = curr_node->link[cmp < 0];
  212. }
  213. return NULL;
  214. }
  215. /* initialize tree traversal
  216. * (re-)sets trav structure
  217. * returns 0
  218. */
  219. int rbtree_init_trav(struct RB_TRAV *trav, struct RB_TREE *tree)
  220. {
  221. assert(trav && tree);
  222. trav->tree = tree;
  223. trav->curr_node = tree->root;
  224. trav->first = 1;
  225. trav->top = 0;
  226. return 0;
  227. }
  228. /* traverse the tree in ascending order
  229. * useful to get all items in the tree non-recursively
  230. * struct RB_TRAV *trav needs to be initialized first
  231. * returns pointer to data, NULL when finished
  232. */
  233. void *rbtree_traverse(struct RB_TRAV *trav)
  234. {
  235. assert(trav);
  236. if (trav->curr_node == NULL) {
  237. if (trav->first)
  238. G_debug(1, "RB tree: empty tree");
  239. else
  240. G_debug(1, "RB tree: finished traversing");
  241. return NULL;
  242. }
  243. if (!trav->first)
  244. return rbtree_next(trav);
  245. else {
  246. trav->first = 0;
  247. return rbtree_first(trav);
  248. }
  249. }
  250. /* find start point to traverse the tree in ascending order
  251. * useful to get a selection of items in the tree
  252. * magnitudes faster than traversing the whole tree
  253. * may return first item that's smaller or first item that's larger
  254. * struct RB_TRAV *trav needs to be initialized first
  255. * returns pointer to data, NULL when finished
  256. */
  257. void *rbtree_traverse_start(struct RB_TRAV *trav, const void *data)
  258. {
  259. int dir = 0;
  260. assert(trav && data);
  261. if (trav->curr_node == NULL) {
  262. if (trav->first)
  263. G_warning("RB tree: empty tree");
  264. else
  265. G_warning("RB tree: finished traversing");
  266. return NULL;
  267. }
  268. if (!trav->first)
  269. return rbtree_next(trav);
  270. /* else first time, get start node */
  271. trav->first = 0;
  272. trav->top = 0;
  273. while (trav->curr_node != NULL) {
  274. dir = trav->tree->rb_compare(trav->curr_node->data, data);
  275. /* exact match, great! */
  276. if (dir == 0)
  277. return trav->curr_node->data;
  278. else {
  279. dir = dir < 0;
  280. /* end of branch, also reached if
  281. * smallest item is larger than search template or
  282. * largest item is smaller than search template */
  283. if (trav->curr_node->link[dir] == NULL)
  284. return trav->curr_node->data;
  285. trav->up[trav->top++] = trav->curr_node;
  286. trav->curr_node = trav->curr_node->link[dir];
  287. }
  288. }
  289. return NULL; /* should not happen */
  290. }
  291. /* two functions needed to fully traverse the tree: initialize and continue
  292. * useful to get all items in the tree non-recursively
  293. * this one here uses a stack
  294. * parent pointers or threads would also be possible
  295. * but these would need to be added to RB_NODE
  296. * -> more memory needed for standard operations
  297. */
  298. /* start traversing the tree
  299. * returns pointer to smallest data item
  300. */
  301. void *rbtree_first(struct RB_TRAV *trav)
  302. {
  303. /* get smallest item */
  304. while (trav->curr_node->link[0] != NULL) {
  305. trav->up[trav->top++] = trav->curr_node;
  306. trav->curr_node = trav->curr_node->link[0];
  307. }
  308. return trav->curr_node->data; /* return smallest item */
  309. }
  310. /* continue traversing the tree in ascending order
  311. * returns pointer to data item, NULL when finished
  312. */
  313. void *rbtree_next(struct RB_TRAV *trav)
  314. {
  315. if (trav->curr_node->link[1] != NULL) {
  316. /* something on the right side: larger item */
  317. trav->up[trav->top++] = trav->curr_node;
  318. trav->curr_node = trav->curr_node->link[1];
  319. /* go down, find smallest item in this branch */
  320. while (trav->curr_node->link[0] != NULL) {
  321. trav->up[trav->top++] = trav->curr_node;
  322. trav->curr_node = trav->curr_node->link[0];
  323. }
  324. }
  325. else {
  326. /* at smallest item in this branch, go back up */
  327. struct RB_NODE *last;
  328. do {
  329. if (trav->top == 0) {
  330. trav->curr_node = NULL;
  331. break;
  332. }
  333. last = trav->curr_node;
  334. trav->curr_node = trav->up[--trav->top];
  335. } while (last == trav->curr_node->link[1]);
  336. }
  337. if (trav->curr_node != NULL) {
  338. return trav->curr_node->data;
  339. }
  340. else
  341. return NULL; /* finished traversing */
  342. }
  343. /* destroy the tree */
  344. void rbtree_destroy(struct RB_TREE *tree)
  345. {
  346. rbtree_destroy2(tree->root);
  347. G_free(tree);
  348. }
  349. void rbtree_destroy2(struct RB_NODE *root)
  350. {
  351. if (root != NULL) {
  352. rbtree_destroy2(root->link[0]);
  353. rbtree_destroy2(root->link[1]);
  354. G_free(root->data);
  355. G_free(root);
  356. }
  357. }
  358. /* used for debugging: check for errors in tree structure */
  359. int rbtree_debug(struct RB_TREE *tree, struct RB_NODE *root)
  360. {
  361. int lh, rh;
  362. if (root == NULL)
  363. return 1;
  364. else {
  365. struct RB_NODE *ln = root->link[0];
  366. struct RB_NODE *rn = root->link[1];
  367. int lcmp = 0, rcmp = 0;
  368. /* Consecutive red links */
  369. if (is_red(root)) {
  370. if (is_red(ln) || is_red(rn)) {
  371. G_warning("Red Black Tree debugging: Red violation");
  372. return 0;
  373. }
  374. }
  375. lh = rbtree_debug(tree, ln);
  376. rh = rbtree_debug(tree, rn);
  377. if (ln) {
  378. lcmp = tree->rb_compare(ln->data, root->data);
  379. }
  380. if (rn) {
  381. rcmp = tree->rb_compare(rn->data, root->data);
  382. }
  383. /* Invalid binary search tree:
  384. * left node >= parent or right node <= parent */
  385. if ((ln != NULL && lcmp > -1)
  386. || (rn != NULL && rcmp < 1)) {
  387. G_warning("Red Black Tree debugging: Binary tree violation");
  388. return 0;
  389. }
  390. /* Black height mismatch */
  391. if (lh != 0 && rh != 0 && lh != rh) {
  392. G_warning("Red Black Tree debugging: Black violation");
  393. return 0;
  394. }
  395. /* Only count black links */
  396. if (lh != 0 && rh != 0)
  397. return is_red(root) ? lh : lh + 1;
  398. else
  399. return 0;
  400. }
  401. }
  402. /*******************************************************
  403. * *
  404. * internal functions for Red Black Tree maintenance *
  405. * *
  406. *******************************************************/
  407. /* add a new node to the tree */
  408. struct RB_NODE *rbtree_make_node(size_t datasize, void *data)
  409. {
  410. struct RB_NODE *new_node = G_malloc(sizeof(*new_node));
  411. if (new_node == NULL)
  412. G_fatal_error("RB Search Tree: Out of memory!");
  413. new_node->data = G_malloc(datasize);
  414. if (new_node->data == NULL)
  415. G_fatal_error("RB Search Tree: Out of memory!");
  416. memcpy(new_node->data, data, datasize);
  417. new_node->red = 1; /* 1 is red, 0 is black */
  418. new_node->link[0] = NULL;
  419. new_node->link[1] = NULL;
  420. return new_node;
  421. }
  422. /* check for red violation */
  423. int is_red(struct RB_NODE *root)
  424. {
  425. if (root)
  426. return root->red == 1;
  427. return 0;
  428. }
  429. /* single rotation */
  430. struct RB_NODE *rbtree_single(struct RB_NODE *root, int dir)
  431. {
  432. struct RB_NODE *newroot = root->link[!dir];
  433. root->link[!dir] = newroot->link[dir];
  434. newroot->link[dir] = root;
  435. root->red = 1;
  436. newroot->red = 0;
  437. return newroot;
  438. }
  439. /* double rotation */
  440. struct RB_NODE *rbtree_double(struct RB_NODE *root, int dir)
  441. {
  442. root->link[!dir] = rbtree_single(root->link[!dir], !dir);
  443. return rbtree_single(root, dir);
  444. }