rbtree.c 13 KB

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