ngbrtree.c 13 KB

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