avl.c 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /*
  2. * Copyright (C) 2010 Joseph Adams <joeyadams3.14159@gmail.com>
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #include "avl.h"
  23. #include <assert.h>
  24. #include <stdlib.h>
  25. static AvlNode *mkNode(const void *key, const void *value);
  26. static void freeNode(AvlNode *node);
  27. static AvlNode *lookup(const AVL *avl, AvlNode *node, const void *key);
  28. static bool insert(AVL *avl, AvlNode **p, const void *key, const void *value);
  29. static bool remove(AVL *avl, AvlNode **p, const void *key, AvlNode **ret);
  30. static bool removeExtremum(AvlNode **p, int side, AvlNode **ret);
  31. static int sway(AvlNode **p, int sway);
  32. static void balance(AvlNode **p, int side);
  33. static bool checkBalances(AvlNode *node, int *height);
  34. static bool checkOrder(AVL *avl);
  35. static size_t countNode(AvlNode *node);
  36. /*
  37. * Utility macros for converting between
  38. * "balance" values (-1 or 1) and "side" values (0 or 1).
  39. *
  40. * bal(0) == -1
  41. * bal(1) == +1
  42. * side(-1) == 0
  43. * side(+1) == 1
  44. */
  45. #define bal(side) ((side) == 0 ? -1 : 1)
  46. #define side(bal) ((bal) == 1 ? 1 : 0)
  47. static int sign(int cmp)
  48. {
  49. if (cmp < 0)
  50. return -1;
  51. if (cmp == 0)
  52. return 0;
  53. return 1;
  54. }
  55. AVL *avl_new(AvlCompare compare)
  56. {
  57. AVL *avl = malloc(sizeof(*avl));
  58. assert(avl != NULL);
  59. avl->compare = compare;
  60. avl->root = NULL;
  61. avl->count = 0;
  62. return avl;
  63. }
  64. void avl_free(AVL *avl)
  65. {
  66. freeNode(avl->root);
  67. free(avl);
  68. }
  69. void *avl_lookup(const AVL *avl, const void *key)
  70. {
  71. AvlNode *found = lookup(avl, avl->root, key);
  72. return found ? (void*) found->value : NULL;
  73. }
  74. AvlNode *avl_lookup_node(const AVL *avl, const void *key)
  75. {
  76. return lookup(avl, avl->root, key);
  77. }
  78. size_t avl_count(const AVL *avl)
  79. {
  80. return avl->count;
  81. }
  82. bool avl_insert(AVL *avl, const void *key, const void *value)
  83. {
  84. size_t old_count = avl->count;
  85. insert(avl, &avl->root, key, value);
  86. return avl->count != old_count;
  87. }
  88. bool avl_remove(AVL *avl, const void *key)
  89. {
  90. AvlNode *node = NULL;
  91. remove(avl, &avl->root, key, &node);
  92. if (node == NULL) {
  93. return false;
  94. } else {
  95. free(node);
  96. return true;
  97. }
  98. }
  99. static AvlNode *mkNode(const void *key, const void *value)
  100. {
  101. AvlNode *node = malloc(sizeof(*node));
  102. assert(node != NULL);
  103. node->key = key;
  104. node->value = value;
  105. node->lr[0] = NULL;
  106. node->lr[1] = NULL;
  107. node->balance = 0;
  108. return node;
  109. }
  110. static void freeNode(AvlNode *node)
  111. {
  112. if (node) {
  113. freeNode(node->lr[0]);
  114. freeNode(node->lr[1]);
  115. free(node);
  116. }
  117. }
  118. static AvlNode *lookup(const AVL *avl, AvlNode *node, const void *key)
  119. {
  120. int cmp;
  121. if (node == NULL)
  122. return NULL;
  123. cmp = avl->compare(key, node->key);
  124. if (cmp < 0)
  125. return lookup(avl, node->lr[0], key);
  126. if (cmp > 0)
  127. return lookup(avl, node->lr[1], key);
  128. return node;
  129. }
  130. /*
  131. * Insert a key/value into a subtree, rebalancing if necessary.
  132. *
  133. * Return true if the subtree's height increased.
  134. */
  135. static bool insert(AVL *avl, AvlNode **p, const void *key, const void *value)
  136. {
  137. if (*p == NULL) {
  138. *p = mkNode(key, value);
  139. avl->count++;
  140. return true;
  141. } else {
  142. AvlNode *node = *p;
  143. int cmp = sign(avl->compare(key, node->key));
  144. if (cmp == 0) {
  145. node->key = key;
  146. node->value = value;
  147. return false;
  148. }
  149. if (!insert(avl, &node->lr[side(cmp)], key, value))
  150. return false;
  151. /* If tree's balance became -1 or 1, it means the tree's height grew due to insertion. */
  152. return sway(p, cmp) != 0;
  153. }
  154. }
  155. /*
  156. * Remove the node matching the given key.
  157. * If present, return the removed node through *ret .
  158. * The returned node's lr and balance are meaningless.
  159. *
  160. * Return true if the subtree's height decreased.
  161. */
  162. static bool remove(AVL *avl, AvlNode **p, const void *key, AvlNode **ret)
  163. {
  164. if (*p == NULL) {
  165. return false;
  166. } else {
  167. AvlNode *node = *p;
  168. int cmp = sign(avl->compare(key, node->key));
  169. if (cmp == 0) {
  170. *ret = node;
  171. avl->count--;
  172. if (node->lr[0] != NULL && node->lr[1] != NULL) {
  173. AvlNode *replacement;
  174. int side;
  175. bool shrunk;
  176. /* Pick a subtree to pull the replacement from such that
  177. * this node doesn't have to be rebalanced. */
  178. side = node->balance <= 0 ? 0 : 1;
  179. shrunk = removeExtremum(&node->lr[side], 1 - side, &replacement);
  180. replacement->lr[0] = node->lr[0];
  181. replacement->lr[1] = node->lr[1];
  182. replacement->balance = node->balance;
  183. *p = replacement;
  184. if (!shrunk)
  185. return false;
  186. replacement->balance -= bal(side);
  187. /* If tree's balance became 0, it means the tree's height shrank due to removal. */
  188. return replacement->balance == 0;
  189. }
  190. if (node->lr[0] != NULL)
  191. *p = node->lr[0];
  192. else
  193. *p = node->lr[1];
  194. return true;
  195. } else {
  196. if (!remove(avl, &node->lr[side(cmp)], key, ret))
  197. return false;
  198. /* If tree's balance became 0, it means the tree's height shrank due to removal. */
  199. return sway(p, -cmp) == 0;
  200. }
  201. }
  202. }
  203. /*
  204. * Remove either the left-most (if side == 0) or right-most (if side == 1)
  205. * node in a subtree, returning the removed node through *ret .
  206. * The returned node's lr and balance are meaningless.
  207. *
  208. * The subtree must not be empty (i.e. *p must not be NULL).
  209. *
  210. * Return true if the subtree's height decreased.
  211. */
  212. static bool removeExtremum(AvlNode **p, int side, AvlNode **ret)
  213. {
  214. AvlNode *node = *p;
  215. if (node->lr[side] == NULL) {
  216. *ret = node;
  217. *p = node->lr[1 - side];
  218. return true;
  219. }
  220. if (!removeExtremum(&node->lr[side], side, ret))
  221. return false;
  222. /* If tree's balance became 0, it means the tree's height shrank due to removal. */
  223. return sway(p, -bal(side)) == 0;
  224. }
  225. /*
  226. * Rebalance a node if necessary. Think of this function
  227. * as a higher-level interface to balance().
  228. *
  229. * sway must be either -1 or 1, and indicates what was added to
  230. * the balance of this node by a prior operation.
  231. *
  232. * Return the new balance of the subtree.
  233. */
  234. static int sway(AvlNode **p, int sway)
  235. {
  236. if ((*p)->balance != sway)
  237. (*p)->balance += sway;
  238. else
  239. balance(p, side(sway));
  240. return (*p)->balance;
  241. }
  242. /*
  243. * Perform tree rotations on an unbalanced node.
  244. *
  245. * side == 0 means the node's balance is -2 .
  246. * side == 1 means the node's balance is +2 .
  247. */
  248. static void balance(AvlNode **p, int side)
  249. {
  250. AvlNode *node = *p,
  251. *child = node->lr[side];
  252. int opposite = 1 - side;
  253. int bal = bal(side);
  254. if (child->balance != -bal) {
  255. /* Left-left (side == 0) or right-right (side == 1) */
  256. node->lr[side] = child->lr[opposite];
  257. child->lr[opposite] = node;
  258. *p = child;
  259. child->balance -= bal;
  260. node->balance = -child->balance;
  261. } else {
  262. /* Left-right (side == 0) or right-left (side == 1) */
  263. AvlNode *grandchild = child->lr[opposite];
  264. node->lr[side] = grandchild->lr[opposite];
  265. child->lr[opposite] = grandchild->lr[side];
  266. grandchild->lr[side] = child;
  267. grandchild->lr[opposite] = node;
  268. *p = grandchild;
  269. node->balance = 0;
  270. child->balance = 0;
  271. if (grandchild->balance == bal)
  272. node->balance = -bal;
  273. else if (grandchild->balance == -bal)
  274. child->balance = bal;
  275. grandchild->balance = 0;
  276. }
  277. }
  278. /************************* avl_check_invariants() *************************/
  279. bool avl_check_invariants(AVL *avl)
  280. {
  281. int dummy;
  282. return checkBalances(avl->root, &dummy)
  283. && checkOrder(avl)
  284. && countNode(avl->root) == avl->count;
  285. }
  286. static bool checkBalances(AvlNode *node, int *height)
  287. {
  288. if (node) {
  289. int h0, h1;
  290. if (!checkBalances(node->lr[0], &h0))
  291. return false;
  292. if (!checkBalances(node->lr[1], &h1))
  293. return false;
  294. if (node->balance != h1 - h0 || node->balance < -1 || node->balance > 1)
  295. return false;
  296. *height = (h0 > h1 ? h0 : h1) + 1;
  297. return true;
  298. } else {
  299. *height = 0;
  300. return true;
  301. }
  302. }
  303. static bool checkOrder(AVL *avl)
  304. {
  305. AvlIter i;
  306. const void *last = NULL;
  307. bool last_set = false;
  308. avl_foreach(i, avl) {
  309. if (last_set && avl->compare(last, i.key) >= 0)
  310. return false;
  311. last = i.key;
  312. last_set = true;
  313. }
  314. return true;
  315. }
  316. static size_t countNode(AvlNode *node)
  317. {
  318. if (node)
  319. return 1 + countNode(node->lr[0]) + countNode(node->lr[1]);
  320. else
  321. return 0;
  322. }
  323. /************************* Traversal *************************/
  324. void avl_iter_begin(AvlIter *iter, AVL *avl, AvlDirection dir)
  325. {
  326. AvlNode *node = avl->root;
  327. iter->stack_index = 0;
  328. iter->direction = dir;
  329. if (node == NULL) {
  330. iter->key = NULL;
  331. iter->value = NULL;
  332. iter->node = NULL;
  333. return;
  334. }
  335. while (node->lr[dir] != NULL) {
  336. iter->stack[iter->stack_index++] = node;
  337. node = node->lr[dir];
  338. }
  339. iter->key = (void*) node->key;
  340. iter->value = (void*) node->value;
  341. iter->node = node;
  342. }
  343. void avl_iter_next(AvlIter *iter)
  344. {
  345. AvlNode *node = iter->node;
  346. AvlDirection dir = iter->direction;
  347. if (node == NULL)
  348. return;
  349. node = node->lr[1 - dir];
  350. if (node != NULL) {
  351. while (node->lr[dir] != NULL) {
  352. iter->stack[iter->stack_index++] = node;
  353. node = node->lr[dir];
  354. }
  355. } else if (iter->stack_index > 0) {
  356. node = iter->stack[--iter->stack_index];
  357. } else {
  358. iter->key = NULL;
  359. iter->value = NULL;
  360. iter->node = NULL;
  361. return;
  362. }
  363. iter->node = node;
  364. iter->key = (void*) node->key;
  365. iter->value = (void*) node->value;
  366. }