rbtree.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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 <grass/vect/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]) &&
  162. !is_red(s->link[last])) {
  163. /* Color flip */
  164. p->red = 0;
  165. s->red = 1;
  166. q->red = 1;
  167. }
  168. else {
  169. int dir2 = g->link[1] == p;
  170. if (is_red(s->link[last]))
  171. g->link[dir2] = rbtree_double(p, last);
  172. else if (is_red(s->link[!last]))
  173. g->link[dir2] = rbtree_single(p, last);
  174. /* Ensure correct coloring */
  175. q->red = g->link[dir2]->red = 1;
  176. g->link[dir2]->link[0]->red = 0;
  177. g->link[dir2]->link[1]->red = 0;
  178. }
  179. }
  180. }
  181. }
  182. }
  183. /* Replace and remove if found */
  184. if (f != NULL) {
  185. G_free(f->data);
  186. f->data = q->data;
  187. p->link[p->link[1] == q] = q->link[q->link[0] == NULL];
  188. G_free(q);
  189. tree->count--;
  190. removed = 1;
  191. }
  192. else
  193. G_debug(2, "RB tree: data not found in search tree");
  194. /* Update root and make it black */
  195. tree->root = head.link[1];
  196. if ( tree->root != NULL)
  197. tree->root->red = 0;
  198. return removed;
  199. }
  200. /* find data item in tree
  201. * returns pointer to data item if found else NULL
  202. */
  203. void *rbtree_find(struct RB_TREE *tree, const void *data)
  204. {
  205. struct RB_NODE *curr_node = tree->root;
  206. int cmp = 0;
  207. assert(tree && data);
  208. while (curr_node != NULL) {
  209. cmp = tree->rb_compare(curr_node->data, data);
  210. if (cmp == 0)
  211. return curr_node->data; /* found */
  212. else {
  213. curr_node = curr_node->link[cmp < 0];
  214. }
  215. }
  216. return NULL;
  217. }
  218. /* initialize tree traversal
  219. * (re-)sets trav structure
  220. * returns 0
  221. */
  222. int rbtree_init_trav(struct RB_TRAV *trav, struct RB_TREE *tree)
  223. {
  224. assert(trav && tree);
  225. trav->tree = tree;
  226. trav->curr_node = tree->root;
  227. trav->first = 1;
  228. trav->top = 0;
  229. return 0;
  230. }
  231. /* traverse the tree in ascending order
  232. * useful to get all items in the tree non-recursively
  233. * struct RB_TRAV *trav needs to be initialized first
  234. * returns pointer to data, NULL when finished
  235. */
  236. void *rbtree_traverse(struct RB_TRAV *trav)
  237. {
  238. assert(trav);
  239. if (trav->curr_node == NULL) {
  240. if (trav->first)
  241. G_debug(1, "RB tree: empty tree");
  242. else
  243. G_debug(1, "RB tree: finished traversing");
  244. return NULL;
  245. }
  246. if (!trav->first)
  247. return rbtree_next(trav);
  248. else {
  249. trav->first = 0;
  250. return rbtree_first(trav);
  251. }
  252. }
  253. /* find start point to traverse the tree in ascending order
  254. * useful to get a selection of items in the tree
  255. * magnitudes faster than traversing the whole tree
  256. * may return first item that's smaller or first item that's larger
  257. * struct RB_TRAV *trav needs to be initialized first
  258. * returns pointer to data, NULL when finished
  259. */
  260. void *rbtree_traverse_start(struct RB_TRAV *trav, const void *data)
  261. {
  262. int dir = 0;
  263. assert(trav && data);
  264. if (trav->curr_node == NULL) {
  265. if (trav->first)
  266. G_warning("RB tree: empty tree");
  267. else
  268. G_warning("RB tree: finished traversing");
  269. return NULL;
  270. }
  271. if (!trav->first)
  272. return rbtree_next(trav);
  273. /* else first time, get start node */
  274. trav->first = 0;
  275. trav->top = 0;
  276. while (trav->curr_node != NULL) {
  277. dir = trav->tree->rb_compare(trav->curr_node->data, data);
  278. /* exact match, great! */
  279. if (dir == 0)
  280. return trav->curr_node->data;
  281. else {
  282. dir = dir < 0;
  283. /* end of branch, also reached if
  284. * smallest item is larger than search template or
  285. * largest item is smaller than search template */
  286. if (trav->curr_node->link[dir] == NULL)
  287. return trav->curr_node->data;
  288. trav->up[trav->top++] = trav->curr_node;
  289. trav->curr_node = trav->curr_node->link[dir];
  290. }
  291. }
  292. return NULL; /* should not happen */
  293. }
  294. /* two functions needed to fully traverse the tree: initialize and continue
  295. * useful to get all items in the tree non-recursively
  296. * this one here uses a stack
  297. * parent pointers or threads would also be possible
  298. * but these would need to be added to RB_NODE
  299. * -> more memory needed for standard operations
  300. */
  301. /* start traversing the tree
  302. * returns pointer to smallest data item
  303. */
  304. void *rbtree_first(struct RB_TRAV *trav)
  305. {
  306. /* get smallest item */
  307. while (trav->curr_node->link[0] != NULL) {
  308. trav->up[trav->top++] = trav->curr_node;
  309. trav->curr_node = trav->curr_node->link[0];
  310. }
  311. return trav->curr_node->data; /* return smallest item */
  312. }
  313. /* continue traversing the tree in ascending order
  314. * returns pointer to data item, NULL when finished
  315. */
  316. void *rbtree_next(struct RB_TRAV *trav)
  317. {
  318. if (trav->curr_node->link[1] != NULL) {
  319. /* something on the right side: larger item */
  320. trav->up[trav->top++] = trav->curr_node;
  321. trav->curr_node = trav->curr_node->link[1];
  322. /* go down, find smallest item in this branch */
  323. while (trav->curr_node->link[0] != NULL) {
  324. trav->up[trav->top++] = trav->curr_node;
  325. trav->curr_node = trav->curr_node->link[0];
  326. }
  327. }
  328. else {
  329. /* at smallest item in this branch, go back up */
  330. struct RB_NODE *last;
  331. do {
  332. if (trav->top == 0) {
  333. trav->curr_node = NULL;
  334. break;
  335. }
  336. last = trav->curr_node;
  337. trav->curr_node = trav->up[--trav->top];
  338. } while (last == trav->curr_node->link[1]);
  339. }
  340. if (trav->curr_node != NULL) {
  341. return trav->curr_node->data;
  342. }
  343. else
  344. return NULL; /* finished traversing */
  345. }
  346. /* destroy the tree */
  347. void rbtree_destroy(struct RB_TREE *tree) {
  348. rbtree_destroy2(tree->root);
  349. G_free(tree);
  350. }
  351. void rbtree_destroy2(struct RB_NODE *root)
  352. {
  353. if (root != NULL) {
  354. rbtree_destroy2(root->link[0]);
  355. rbtree_destroy2(root->link[1]);
  356. G_free(root->data);
  357. G_free(root);
  358. }
  359. }
  360. /* used for debugging: check for errors in tree structure */
  361. int rbtree_debug(struct RB_TREE *tree, struct RB_NODE *root)
  362. {
  363. int lh, rh;
  364. if (root == NULL)
  365. return 1;
  366. else {
  367. struct RB_NODE *ln = root->link[0];
  368. struct RB_NODE *rn = root->link[1];
  369. int lcmp = 0, rcmp = 0;
  370. /* Consecutive red links */
  371. if (is_red(root)) {
  372. if (is_red(ln) || is_red(rn)) {
  373. G_warning("Red Black Tree debugging: Red violation");
  374. return 0;
  375. }
  376. }
  377. lh = rbtree_debug(tree, ln);
  378. rh = rbtree_debug(tree, rn);
  379. if (ln) {
  380. lcmp = tree->rb_compare(ln->data, root->data);
  381. }
  382. if (rn) {
  383. rcmp = tree->rb_compare(rn->data, root->data);
  384. }
  385. /* Invalid binary search tree:
  386. * left node >= parent or right node <= parent */
  387. if ((ln != NULL && lcmp > -1)
  388. || (rn != NULL && rcmp < 1)) {
  389. G_warning("Red Black Tree debugging: Binary tree violation" );
  390. return 0;
  391. }
  392. /* Black height mismatch */
  393. if (lh != 0 && rh != 0 && lh != rh) {
  394. G_warning("Red Black Tree debugging: Black violation");
  395. return 0;
  396. }
  397. /* Only count black links */
  398. if (lh != 0 && rh != 0)
  399. return is_red(root) ? lh : lh + 1;
  400. else
  401. return 0;
  402. }
  403. }
  404. /*******************************************************
  405. * *
  406. * internal functions for Red Black Tree maintenance *
  407. * *
  408. *******************************************************/
  409. /* add a new node to the tree */
  410. struct RB_NODE *rbtree_make_node(size_t datasize, void *data)
  411. {
  412. struct RB_NODE *new_node = G_malloc(sizeof(*new_node));
  413. if (new_node == NULL)
  414. G_fatal_error("RB Search Tree: Out of memory!");
  415. new_node->data = G_malloc(datasize);
  416. if (new_node->data == NULL)
  417. G_fatal_error("RB Search Tree: Out of memory!");
  418. memcpy(new_node->data, data, datasize);
  419. new_node->red = 1; /* 1 is red, 0 is black */
  420. new_node->link[0] = NULL;
  421. new_node->link[1] = NULL;
  422. return new_node;
  423. }
  424. /* check for red violation */
  425. int is_red(struct RB_NODE *root)
  426. {
  427. if (root)
  428. return root->red == 1;
  429. return 0;
  430. }
  431. /* single rotation */
  432. struct RB_NODE *rbtree_single(struct RB_NODE *root, int dir)
  433. {
  434. struct RB_NODE *newroot = root->link[!dir];
  435. root->link[!dir] = newroot->link[dir];
  436. newroot->link[dir] = root;
  437. root->red = 1;
  438. newroot->red = 0;
  439. return newroot;
  440. }
  441. /* double rotation */
  442. struct RB_NODE *rbtree_double(struct RB_NODE *root, int dir)
  443. {
  444. root->link[!dir] = rbtree_single(root->link[!dir], !dir);
  445. return rbtree_single(root, dir);
  446. }