rbtree.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. q = NULL;
  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. struct RB_NODE *it;
  346. struct RB_NODE *save = tree->root;
  347. /*
  348. Rotate away the left links so that
  349. we can treat this like the destruction
  350. of a linked list
  351. */
  352. while((it = save) != NULL) {
  353. if (it->link[0] == NULL) {
  354. /* No left links, just kill the node and move on */
  355. save = it->link[1];
  356. free(it->data);
  357. it->data = NULL;
  358. free(it);
  359. it = NULL;
  360. }
  361. else {
  362. /* Rotate away the left link and check again */
  363. save = it->link[0];
  364. it->link[0] = save->link[1];
  365. save->link[1] = it;
  366. }
  367. }
  368. free(tree);
  369. tree = NULL;
  370. }
  371. /* used for debugging: check for errors in tree structure */
  372. int rbtree_debug(struct RB_TREE *tree, struct RB_NODE *root)
  373. {
  374. int lh, rh;
  375. if (root == NULL)
  376. return 1;
  377. else {
  378. struct RB_NODE *ln = root->link[0];
  379. struct RB_NODE *rn = root->link[1];
  380. int lcmp = 0, rcmp = 0;
  381. /* Consecutive red links */
  382. if (is_red(root)) {
  383. if (is_red(ln) || is_red(rn)) {
  384. G_warning("Red Black Tree debugging: Red violation");
  385. return 0;
  386. }
  387. }
  388. lh = rbtree_debug(tree, ln);
  389. rh = rbtree_debug(tree, rn);
  390. if (ln) {
  391. lcmp = tree->rb_compare(ln->data, root->data);
  392. }
  393. if (rn) {
  394. rcmp = tree->rb_compare(rn->data, root->data);
  395. }
  396. /* Invalid binary search tree:
  397. * left node >= parent or right node <= parent */
  398. if ((ln != NULL && lcmp > -1)
  399. || (rn != NULL && rcmp < 1)) {
  400. G_warning("Red Black Tree debugging: Binary tree violation");
  401. return 0;
  402. }
  403. /* Black height mismatch */
  404. if (lh != 0 && rh != 0 && lh != rh) {
  405. G_warning("Red Black Tree debugging: Black violation");
  406. return 0;
  407. }
  408. /* Only count black links */
  409. if (lh != 0 && rh != 0)
  410. return is_red(root) ? lh : lh + 1;
  411. else
  412. return 0;
  413. }
  414. }
  415. /*******************************************************
  416. * *
  417. * internal functions for Red Black Tree maintenance *
  418. * *
  419. *******************************************************/
  420. /* add a new node to the tree */
  421. struct RB_NODE *rbtree_make_node(size_t datasize, void *data)
  422. {
  423. struct RB_NODE *new_node = (struct RB_NODE *)malloc(sizeof(*new_node));
  424. if (new_node == NULL)
  425. G_fatal_error("RB Search Tree: Out of memory!");
  426. new_node->data = malloc(datasize);
  427. if (new_node->data == NULL)
  428. G_fatal_error("RB Search Tree: Out of memory!");
  429. memcpy(new_node->data, data, datasize);
  430. new_node->red = 1; /* 1 is red, 0 is black */
  431. new_node->link[0] = NULL;
  432. new_node->link[1] = NULL;
  433. return new_node;
  434. }
  435. /* check for red violation */
  436. int is_red(struct RB_NODE *root)
  437. {
  438. if (root)
  439. return root->red == 1;
  440. return 0;
  441. }
  442. /* single rotation */
  443. struct RB_NODE *rbtree_single(struct RB_NODE *root, int dir)
  444. {
  445. struct RB_NODE *newroot = root->link[!dir];
  446. root->link[!dir] = newroot->link[dir];
  447. newroot->link[dir] = root;
  448. root->red = 1;
  449. newroot->red = 0;
  450. return newroot;
  451. }
  452. /* double rotation */
  453. struct RB_NODE *rbtree_double(struct RB_NODE *root, int dir)
  454. {
  455. root->link[!dir] = rbtree_single(root->link[!dir], !dir);
  456. return rbtree_single(root, dir);
  457. }