rbtree.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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. static struct RB_NODE *rbtree_single(struct RB_NODE *, int);
  35. static struct RB_NODE *rbtree_double(struct RB_NODE *, int);
  36. static void *rbtree_first(struct RB_TRAV *);
  37. static void *rbtree_last(struct RB_TRAV *trav);
  38. static void *rbtree_next(struct RB_TRAV *);
  39. static void *rbtree_previous(struct RB_TRAV *);
  40. static struct RB_NODE *rbtree_make_node(size_t, void *);
  41. static 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 = (struct RB_TREE *)malloc(sizeof(struct RB_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, 0, {0, 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, 0, {0, 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. free(f->data);
  185. f->data = q->data;
  186. p->link[p->link[1] == q] = q->link[q->link[0] == NULL];
  187. free(q);
  188. q = NULL;
  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;
  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. curr_node = curr_node->link[cmp < 0];
  213. }
  214. return NULL;
  215. }
  216. /* initialize tree traversal
  217. * (re-)sets trav structure
  218. * returns 0
  219. */
  220. int rbtree_init_trav(struct RB_TRAV *trav, struct RB_TREE *tree)
  221. {
  222. assert(trav && tree);
  223. trav->tree = tree;
  224. trav->curr_node = tree->root;
  225. trav->first = 1;
  226. trav->top = 0;
  227. return 0;
  228. }
  229. /* traverse the tree in ascending order
  230. * useful to get all items in the tree non-recursively
  231. * struct RB_TRAV *trav needs to be initialized first
  232. * returns pointer to data, NULL when finished
  233. */
  234. void *rbtree_traverse(struct RB_TRAV *trav)
  235. {
  236. assert(trav);
  237. if (trav->curr_node == NULL) {
  238. if (trav->first)
  239. G_debug(1, "RB tree: empty tree");
  240. else
  241. G_debug(1, "RB tree: finished traversing");
  242. return NULL;
  243. }
  244. if (!trav->first)
  245. return rbtree_next(trav);
  246. else {
  247. trav->first = 0;
  248. return rbtree_first(trav);
  249. }
  250. }
  251. /* traverse the tree in descending order
  252. * useful to get all items in the tree non-recursively
  253. * struct RB_TRAV *trav needs to be initialized first
  254. * returns pointer to data, NULL when finished
  255. */
  256. void *rbtree_traverse_backwd(struct RB_TRAV *trav)
  257. {
  258. assert(trav);
  259. if (trav->curr_node == NULL) {
  260. if (trav->first)
  261. G_debug(1, "RB tree: empty tree");
  262. else
  263. G_debug(1, "RB tree: finished traversing");
  264. return NULL;
  265. }
  266. if (!trav->first)
  267. return rbtree_previous(trav);
  268. else {
  269. trav->first = 0;
  270. return rbtree_last(trav);
  271. }
  272. }
  273. /* find start point to traverse the tree in ascending order
  274. * useful to get a selection of items in the tree
  275. * magnitudes faster than traversing the whole tree
  276. * may return first item that's smaller or first item that's larger
  277. * struct RB_TRAV *trav needs to be initialized first
  278. * returns pointer to data, NULL when finished
  279. */
  280. void *rbtree_traverse_start(struct RB_TRAV *trav, const void *data)
  281. {
  282. int dir = 0;
  283. assert(trav && data);
  284. if (trav->curr_node == NULL) {
  285. if (trav->first)
  286. G_warning("RB tree: empty tree");
  287. else
  288. G_warning("RB tree: finished traversing");
  289. return NULL;
  290. }
  291. if (!trav->first)
  292. return rbtree_next(trav);
  293. /* else first time, get start node */
  294. trav->first = 0;
  295. trav->top = 0;
  296. while (trav->curr_node != NULL) {
  297. dir = trav->tree->rb_compare(trav->curr_node->data, data);
  298. /* exact match, great! */
  299. if (dir == 0)
  300. return trav->curr_node->data;
  301. else {
  302. dir = dir < 0;
  303. /* end of branch, also reached if
  304. * smallest item is larger than search template or
  305. * largest item is smaller than search template */
  306. if (trav->curr_node->link[dir] == NULL)
  307. return trav->curr_node->data;
  308. trav->up[trav->top++] = trav->curr_node;
  309. trav->curr_node = trav->curr_node->link[dir];
  310. }
  311. }
  312. return NULL; /* should not happen */
  313. }
  314. /* two functions needed to fully traverse the tree: initialize and continue
  315. * useful to get all items in the tree non-recursively
  316. * this one here uses a stack
  317. * parent pointers or threads would also be possible
  318. * but these would need to be added to RB_NODE
  319. * -> more memory needed for standard operations
  320. */
  321. /* start traversing the tree
  322. * returns pointer to smallest data item
  323. */
  324. static void *rbtree_first(struct RB_TRAV *trav)
  325. {
  326. /* get smallest item */
  327. while (trav->curr_node->link[0] != NULL) {
  328. trav->up[trav->top++] = trav->curr_node;
  329. trav->curr_node = trav->curr_node->link[0];
  330. }
  331. return trav->curr_node->data; /* return smallest item */
  332. }
  333. /* start traversing the tree
  334. * returns pointer to largest data item
  335. */
  336. static void *rbtree_last(struct RB_TRAV *trav)
  337. {
  338. /* get smallest item */
  339. while (trav->curr_node->link[1] != NULL) {
  340. trav->up[trav->top++] = trav->curr_node;
  341. trav->curr_node = trav->curr_node->link[1];
  342. }
  343. return trav->curr_node->data; /* return smallest item */
  344. }
  345. /* continue traversing the tree in ascending order
  346. * returns pointer to data item, NULL when finished
  347. */
  348. void *rbtree_next(struct RB_TRAV *trav)
  349. {
  350. if (trav->curr_node->link[1] != NULL) {
  351. /* something on the right side: larger item */
  352. trav->up[trav->top++] = trav->curr_node;
  353. trav->curr_node = trav->curr_node->link[1];
  354. /* go down, find smallest item in this branch */
  355. while (trav->curr_node->link[0] != NULL) {
  356. trav->up[trav->top++] = trav->curr_node;
  357. trav->curr_node = trav->curr_node->link[0];
  358. }
  359. }
  360. else {
  361. /* at smallest item in this branch, go back up */
  362. struct RB_NODE *last;
  363. do {
  364. if (trav->top == 0) {
  365. trav->curr_node = NULL;
  366. break;
  367. }
  368. last = trav->curr_node;
  369. trav->curr_node = trav->up[--trav->top];
  370. } while (last == trav->curr_node->link[1]);
  371. }
  372. if (trav->curr_node != NULL) {
  373. return trav->curr_node->data;
  374. }
  375. else
  376. return NULL; /* finished traversing */
  377. }
  378. /* continue traversing the tree in descending order
  379. * returns pointer to data item, NULL when finished
  380. */
  381. void *rbtree_previous(struct RB_TRAV *trav)
  382. {
  383. if (trav->curr_node->link[0] != NULL) {
  384. /* something on the left side: smaller item */
  385. trav->up[trav->top++] = trav->curr_node;
  386. trav->curr_node = trav->curr_node->link[0];
  387. /* go down, find largest item in this branch */
  388. while (trav->curr_node->link[1] != NULL) {
  389. trav->up[trav->top++] = trav->curr_node;
  390. trav->curr_node = trav->curr_node->link[1];
  391. }
  392. }
  393. else {
  394. /* at largest item in this branch, go back up */
  395. struct RB_NODE *last;
  396. do {
  397. if (trav->top == 0) {
  398. trav->curr_node = NULL;
  399. break;
  400. }
  401. last = trav->curr_node;
  402. trav->curr_node = trav->up[--trav->top];
  403. } while (last == trav->curr_node->link[0]);
  404. }
  405. if (trav->curr_node != NULL) {
  406. return trav->curr_node->data;
  407. }
  408. else
  409. return NULL; /* finished traversing */
  410. }
  411. /* clear the tree, removing all entries */
  412. void rbtree_clear(struct RB_TREE *tree)
  413. {
  414. struct RB_NODE *it;
  415. struct RB_NODE *save = tree->root;
  416. /*
  417. Rotate away the left links so that
  418. we can treat this like the destruction
  419. of a linked list
  420. */
  421. while((it = save) != NULL) {
  422. if (it->link[0] == NULL) {
  423. /* No left links, just kill the node and move on */
  424. save = it->link[1];
  425. free(it->data);
  426. it->data = NULL;
  427. free(it);
  428. it = NULL;
  429. }
  430. else {
  431. /* Rotate away the left link and check again */
  432. save = it->link[0];
  433. it->link[0] = save->link[1];
  434. save->link[1] = it;
  435. }
  436. }
  437. tree->root = NULL;
  438. }
  439. /* destroy the tree */
  440. void rbtree_destroy(struct RB_TREE *tree)
  441. {
  442. /* remove all entries */
  443. rbtree_clear(tree);
  444. free(tree);
  445. tree = NULL;
  446. }
  447. /* used for debugging: check for errors in tree structure */
  448. int rbtree_debug(struct RB_TREE *tree, struct RB_NODE *root)
  449. {
  450. int lh, rh;
  451. if (root == NULL)
  452. return 1;
  453. else {
  454. struct RB_NODE *ln = root->link[0];
  455. struct RB_NODE *rn = root->link[1];
  456. int lcmp = 0, rcmp = 0;
  457. /* Consecutive red links */
  458. if (is_red(root)) {
  459. if (is_red(ln) || is_red(rn)) {
  460. G_warning("Red Black Tree debugging: Red violation");
  461. return 0;
  462. }
  463. }
  464. lh = rbtree_debug(tree, ln);
  465. rh = rbtree_debug(tree, rn);
  466. if (ln) {
  467. lcmp = tree->rb_compare(ln->data, root->data);
  468. }
  469. if (rn) {
  470. rcmp = tree->rb_compare(rn->data, root->data);
  471. }
  472. /* Invalid binary search tree:
  473. * left node >= parent or right node <= parent */
  474. if ((ln != NULL && lcmp > -1)
  475. || (rn != NULL && rcmp < 1)) {
  476. G_warning("Red Black Tree debugging: Binary tree violation");
  477. return 0;
  478. }
  479. /* Black height mismatch */
  480. if (lh != 0 && rh != 0 && lh != rh) {
  481. G_warning("Red Black Tree debugging: Black violation");
  482. return 0;
  483. }
  484. /* Only count black links */
  485. if (lh != 0 && rh != 0)
  486. return is_red(root) ? lh : lh + 1;
  487. else
  488. return 0;
  489. }
  490. }
  491. /*******************************************************
  492. * *
  493. * internal functions for Red Black Tree maintenance *
  494. * *
  495. *******************************************************/
  496. /* add a new node to the tree */
  497. static struct RB_NODE *rbtree_make_node(size_t datasize, void *data)
  498. {
  499. struct RB_NODE *new_node = (struct RB_NODE *)malloc(sizeof(*new_node));
  500. if (new_node == NULL)
  501. G_fatal_error("RB Search Tree: Out of memory!");
  502. new_node->data = malloc(datasize);
  503. if (new_node->data == NULL)
  504. G_fatal_error("RB Search Tree: Out of memory!");
  505. memcpy(new_node->data, data, datasize);
  506. new_node->red = 1; /* 1 is red, 0 is black */
  507. new_node->link[0] = NULL;
  508. new_node->link[1] = NULL;
  509. return new_node;
  510. }
  511. /* check for red violation */
  512. static int is_red(struct RB_NODE *root)
  513. {
  514. if (root)
  515. return root->red == 1;
  516. return 0;
  517. }
  518. /* single rotation */
  519. static struct RB_NODE *rbtree_single(struct RB_NODE *root, int dir)
  520. {
  521. struct RB_NODE *newroot = root->link[!dir];
  522. root->link[!dir] = newroot->link[dir];
  523. newroot->link[dir] = root;
  524. root->red = 1;
  525. newroot->red = 0;
  526. return newroot;
  527. }
  528. /* double rotation */
  529. static struct RB_NODE *rbtree_double(struct RB_NODE *root, int dir)
  530. {
  531. root->link[!dir] = rbtree_single(root->link[!dir], !dir);
  532. return rbtree_single(root, dir);
  533. }