rbtree.c 12 KB

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