2 * avl_tree.c - intrusive, nonrecursive AVL tree data structure (self-balancing
3 * binary search tree), implementation file
5 * The following copying information applies to this specific source code file:
7 * Written in 2014 by Eric Biggers <ebiggers3@gmail.com>
9 * To the extent possible under law, the author(s) have dedicated all copyright
10 * and related and neighboring rights to this software to the public domain
11 * worldwide via the Creative Commons Zero 1.0 Universal Public Domain
12 * Dedication (the "CC0").
14 * This software is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the CC0 for more details.
18 * You should have received a copy of the CC0 along with this software; if not
19 * see <http://creativecommons.org/publicdomain/zero/1.0/>.
26 #include "wimlib/avl_tree.h"
28 /* Starts an in-order traversal of the tree: returns the least-valued node, or
29 * NULL if the tree is empty. */
30 struct avl_tree_node *
31 avl_tree_first_in_order(const struct avl_tree_node *root)
33 const struct avl_tree_node *first = root;
38 return (struct avl_tree_node *)first;
41 /* Continues an in-order traversal of the tree: returns the next-greatest-valued
42 * node, or NULL if there is none. */
43 struct avl_tree_node *
44 avl_tree_next_in_order(const struct avl_tree_node *prev)
46 const struct avl_tree_node *next;
49 for (next = prev->right;
54 for (next = avl_get_parent(prev);
55 next && prev == next->right;
56 prev = next, next = avl_get_parent(next))
58 return (struct avl_tree_node *)next;
61 /* Starts a postorder traversal of the tree. */
62 struct avl_tree_node *
63 avl_tree_first_in_postorder(const struct avl_tree_node *root)
65 const struct avl_tree_node *first = root;
68 while (first->left || first->right)
69 first = first->left ? first->left : first->right;
71 return (struct avl_tree_node *)first;
74 /* Continues a postorder traversal of the tree. @prev will not be deferenced as
75 * it's allowed that its memory has been freed; @prev_parent must be its saved
76 * parent node. Returns NULL if there are no more nodes (i.e. @prev was the
77 * root of the tree). */
78 struct avl_tree_node *
79 avl_tree_next_in_postorder(const struct avl_tree_node *prev,
80 const struct avl_tree_node *prev_parent)
82 const struct avl_tree_node *next = prev_parent;
84 if (next && prev == next->left && next->right)
85 for (next = next->right;
86 next->left || next->right;
87 next = next->left ? next->left : next->right)
89 return (struct avl_tree_node *)next;
92 /* Returns the left child (sign < 0) or the right child (sign > 0) of the
93 * specified AVL tree node.
94 * Note: for all calls of this, 'sign' is constant at compilation time,
95 * so the compiler can remove the conditional. */
96 static forceinline struct avl_tree_node *
97 avl_get_child(const struct avl_tree_node *parent, int sign)
102 return parent->right;
105 /* Sets the left child (sign < 0) or the right child (sign > 0) of the
106 * specified AVL tree node.
107 * Note: for all calls of this, 'sign' is constant at compilation time,
108 * so the compiler can remove the conditional. */
109 static forceinline void
110 avl_set_child(struct avl_tree_node *parent, int sign,
111 struct avl_tree_node *child)
114 parent->left = child;
116 parent->right = child;
119 /* Sets the parent and balance factor of the specified AVL tree node. */
120 static forceinline void
121 avl_set_parent_balance(struct avl_tree_node *node, struct avl_tree_node *parent,
124 node->parent_balance = (uintptr_t)parent | (balance_factor + 1);
127 /* Sets the parent of the specified AVL tree node. */
128 static forceinline void
129 avl_set_parent(struct avl_tree_node *node, struct avl_tree_node *parent)
131 node->parent_balance = (uintptr_t)parent | (node->parent_balance & 3);
134 /* Returns the balance factor of the specified AVL tree node --- that is, the
135 * height of its right subtree minus the height of its left subtree. */
136 static forceinline int
137 avl_get_balance_factor(const struct avl_tree_node *node)
139 return (int)(node->parent_balance & 3) - 1;
142 /* Adds @amount to the balance factor of the specified AVL tree node.
143 * The caller must ensure this still results in a valid balance factor
145 static forceinline void
146 avl_adjust_balance_factor(struct avl_tree_node *node, int amount)
148 node->parent_balance += amount;
151 static forceinline void
152 avl_replace_child(struct avl_tree_node **root_ptr,
153 struct avl_tree_node *parent,
154 struct avl_tree_node *old_child,
155 struct avl_tree_node *new_child)
158 if (old_child == parent->left)
159 parent->left = new_child;
161 parent->right = new_child;
163 *root_ptr = new_child;
168 * Template for performing a single rotation ---
170 * sign > 0: Rotate clockwise (right) rooted at A:
180 * (nodes marked with ? may not exist)
182 * sign < 0: Rotate counterclockwise (left) rooted at A:
192 * This updates pointers but not balance factors!
194 static forceinline void
195 avl_rotate(struct avl_tree_node ** const root_ptr,
196 struct avl_tree_node * const A, const int sign)
198 struct avl_tree_node * const B = avl_get_child(A, -sign);
199 struct avl_tree_node * const E = avl_get_child(B, +sign);
200 struct avl_tree_node * const P = avl_get_parent(A);
202 avl_set_child(A, -sign, E);
203 avl_set_parent(A, B);
205 avl_set_child(B, +sign, A);
206 avl_set_parent(B, P);
209 avl_set_parent(E, A);
211 avl_replace_child(root_ptr, P, A, B);
215 * Template for performing a double rotation ---
217 * sign > 0: Rotate counterclockwise (left) rooted at B, then
218 * clockwise (right) rooted at A:
224 * B C? => E C? => B A
226 * D? E B G? D? F?G? C?
230 * (nodes marked with ? may not exist)
232 * sign < 0: Rotate clockwise (right) rooted at B, then
233 * counterclockwise (left) rooted at A:
239 * C? B => C? E => A B
241 * E D? G? B C? G?F? D?
245 * Returns a pointer to E and updates balance factors. Except for those
246 * two things, this function is equivalent to:
247 * avl_rotate(root_ptr, B, -sign);
248 * avl_rotate(root_ptr, A, +sign);
250 * See comment in avl_handle_subtree_growth() for explanation of balance
253 static forceinline struct avl_tree_node *
254 avl_do_double_rotate(struct avl_tree_node ** const root_ptr,
255 struct avl_tree_node * const B,
256 struct avl_tree_node * const A, const int sign)
258 struct avl_tree_node * const E = avl_get_child(B, +sign);
259 struct avl_tree_node * const F = avl_get_child(E, -sign);
260 struct avl_tree_node * const G = avl_get_child(E, +sign);
261 struct avl_tree_node * const P = avl_get_parent(A);
262 const int e = avl_get_balance_factor(E);
264 avl_set_child(A, -sign, G);
265 avl_set_parent_balance(A, E, ((sign * e >= 0) ? 0 : -e));
267 avl_set_child(B, +sign, F);
268 avl_set_parent_balance(B, E, ((sign * e <= 0) ? 0 : -e));
270 avl_set_child(E, +sign, A);
271 avl_set_child(E, -sign, B);
272 avl_set_parent_balance(E, P, 0);
275 avl_set_parent(G, A);
278 avl_set_parent(F, B);
280 avl_replace_child(root_ptr, P, A, E);
286 * This function handles the growth of a subtree due to an insertion.
289 * Location of the tree's root pointer.
292 * A subtree that has increased in height by 1 due to an insertion.
295 * Parent of @node; must not be NULL.
298 * -1 if @node is the left child of @parent;
299 * +1 if @node is the right child of @parent.
301 * This function will adjust @parent's balance factor, then do a (single
302 * or double) rotation if necessary. The return value will be %true if
303 * the full AVL tree is now adequately balanced, or %false if the subtree
304 * rooted at @parent is now adequately balanced but has increased in
305 * height by 1, so the caller should continue up the tree.
307 * Note that if %false is returned, no rotation will have been done.
308 * Indeed, a single node insertion cannot require that more than one
309 * (single or double) rotation be done.
311 static forceinline bool
312 avl_handle_subtree_growth(struct avl_tree_node ** const root_ptr,
313 struct avl_tree_node * const node,
314 struct avl_tree_node * const parent,
317 int old_balance_factor, new_balance_factor;
319 old_balance_factor = avl_get_balance_factor(parent);
321 if (old_balance_factor == 0) {
322 avl_adjust_balance_factor(parent, sign);
323 /* @parent is still sufficiently balanced (-1 or +1
324 * balance factor), but must have increased in height.
325 * Continue up the tree. */
329 new_balance_factor = old_balance_factor + sign;
331 if (new_balance_factor == 0) {
332 avl_adjust_balance_factor(parent, sign);
333 /* @parent is now perfectly balanced (0 balance factor).
334 * It cannot have increased in height, so there is
335 * nothing more to do. */
339 /* @parent is too left-heavy (new_balance_factor == -2) or
340 * too right-heavy (new_balance_factor == +2). */
342 /* Test whether @node is left-heavy (-1 balance factor) or
343 * right-heavy (+1 balance factor).
344 * Note that it cannot be perfectly balanced (0 balance factor)
345 * because here we are under the invariant that @node has
346 * increased in height due to the insertion. */
347 if (sign * avl_get_balance_factor(node) > 0) {
349 /* @node (B below) is heavy in the same direction @parent
350 * (A below) is heavy.
352 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
353 * The comment, diagram, and equations below assume sign < 0.
354 * The other case is symmetric!
355 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
357 * Do a clockwise rotation rooted at @parent (A below):
367 * Before the rotation:
370 * Let x = height(C). Then:
374 * max(height(F), height(G)) = x.
376 * After the rotation:
377 * height(D) = max(height(F), height(G)) + 1
379 * height(A) = max(height(E), height(C)) + 1
380 * = max(x, x) + 1 = x + 1
384 avl_rotate(root_ptr, parent, -sign);
386 /* Equivalent to setting @parent's balance factor to 0. */
387 avl_adjust_balance_factor(parent, -sign); /* A */
389 /* Equivalent to setting @node's balance factor to 0. */
390 avl_adjust_balance_factor(node, -sign); /* B */
392 /* @node (B below) is heavy in the direction opposite
393 * from the direction @parent (A below) is heavy.
395 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
396 * The comment, diagram, and equations below assume sign < 0.
397 * The other case is symmetric!
398 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
400 * Do a counterblockwise rotation rooted at @node (B below),
401 * then a clockwise rotation rooted at @parent (A below):
405 * B C? => E C? => B A
407 * D? E B G? D? F?G? C?
411 * Before the rotation:
414 * Let x = height(C). Then:
418 * max(height(F), height(G)) = x
420 * After both rotations:
421 * height(A) = max(height(G), height(C)) + 1
423 * balance(A) = balance(E{orig}) >= 0 ? 0 : -balance(E{orig})
424 * height(B) = max(height(D), height(F)) + 1
426 * balance(B) = balance(E{orig} <= 0) ? 0 : -balance(E{orig})
431 avl_do_double_rotate(root_ptr, node, parent, -sign);
434 /* Height after rotation is unchanged; nothing more to do. */
438 /* Rebalance the tree after insertion of the specified node. */
440 avl_tree_rebalance_after_insert(struct avl_tree_node **root_ptr,
441 struct avl_tree_node *inserted)
443 struct avl_tree_node *node, *parent;
446 inserted->left = NULL;
447 inserted->right = NULL;
451 /* Adjust balance factor of new node's parent.
452 * No rotation will need to be done at this level. */
454 parent = avl_get_parent(node);
458 if (node == parent->left)
459 avl_adjust_balance_factor(parent, -1);
461 avl_adjust_balance_factor(parent, +1);
463 if (avl_get_balance_factor(parent) == 0)
464 /* @parent did not change in height. Nothing more to do. */
467 /* The subtree rooted at @parent increased in height by 1. */
470 /* Adjust balance factor of next ancestor. */
473 parent = avl_get_parent(node);
477 /* The subtree rooted at @node has increased in height by 1. */
478 if (node == parent->left)
479 done = avl_handle_subtree_growth(root_ptr, node,
482 done = avl_handle_subtree_growth(root_ptr, node,
488 * This function handles the shrinkage of a subtree due to a deletion.
491 * Location of the tree's root pointer.
494 * A node in the tree, exactly one of whose subtrees has decreased
495 * in height by 1 due to a deletion. (This includes the case where
496 * one of the child pointers has become NULL, since we can consider
497 * the "NULL" subtree to have a height of 0.)
500 * +1 if the left subtree of @parent has decreased in height by 1;
501 * -1 if the right subtree of @parent has decreased in height by 1.
504 * If the return value is not NULL, this will be set to %true if the
505 * left subtree of the returned node has decreased in height by 1,
506 * or %false if the right subtree of the returned node has decreased
509 * This function will adjust @parent's balance factor, then do a (single
510 * or double) rotation if necessary. The return value will be NULL if
511 * the full AVL tree is now adequately balanced, or a pointer to the
512 * parent of @parent if @parent is now adequately balanced but has
513 * decreased in height by 1. Also in the latter case, *left_deleted_ret
516 static forceinline struct avl_tree_node *
517 avl_handle_subtree_shrink(struct avl_tree_node ** const root_ptr,
518 struct avl_tree_node *parent,
520 bool * const left_deleted_ret)
522 struct avl_tree_node *node;
523 int old_balance_factor, new_balance_factor;
525 old_balance_factor = avl_get_balance_factor(parent);
527 if (old_balance_factor == 0) {
528 /* Prior to the deletion, the subtree rooted at
529 * @parent was perfectly balanced. It's now
530 * unbalanced by 1, but that's okay and its height
531 * hasn't changed. Nothing more to do. */
532 avl_adjust_balance_factor(parent, sign);
536 new_balance_factor = old_balance_factor + sign;
538 if (new_balance_factor == 0) {
539 /* The subtree rooted at @parent is now perfectly
540 * balanced, whereas before the deletion it was
541 * unbalanced by 1. Its height must have decreased
542 * by 1. No rotation is needed at this location,
543 * but continue up the tree. */
544 avl_adjust_balance_factor(parent, sign);
547 /* @parent is too left-heavy (new_balance_factor == -2) or
548 * too right-heavy (new_balance_factor == +2). */
550 node = avl_get_child(parent, sign);
552 /* The rotations below are similar to those done during
553 * insertion (see avl_handle_subtree_growth()), so full
554 * comments are not provided. The only new case is the
555 * one where @node has a balance factor of 0, and that is
558 if (sign * avl_get_balance_factor(node) >= 0) {
560 avl_rotate(root_ptr, parent, -sign);
562 if (avl_get_balance_factor(node) == 0) {
564 * @node (B below) is perfectly balanced.
566 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
567 * The comment, diagram, and equations
568 * below assume sign < 0. The other case
570 * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
572 * Do a clockwise rotation rooted at
583 * Before the rotation:
586 * Let x = height(C). Then:
590 * max(height(F), height(G)) = x.
592 * After the rotation:
593 * height(D) = max(height(F), height(G)) + 1
595 * height(A) = max(height(E), height(C)) + 1
596 * = max(x + 1, x) + 1 = x + 2
601 /* A: -2 => -1 (sign < 0)
602 * or +2 => +1 (sign > 0)
603 * No change needed --- that's the same as
604 * old_balance_factor. */
606 /* B: 0 => +1 (sign < 0)
607 * or 0 => -1 (sign > 0) */
608 avl_adjust_balance_factor(node, -sign);
610 /* Height is unchanged; nothing more to do. */
613 avl_adjust_balance_factor(parent, -sign);
614 avl_adjust_balance_factor(node, -sign);
617 node = avl_do_double_rotate(root_ptr, node,
621 parent = avl_get_parent(node);
623 *left_deleted_ret = (node == parent->left);
627 /* Swaps node X, which must have 2 children, with its in-order successor, then
628 * unlinks node X. Returns the parent of X just before unlinking, without its
629 * balance factor having been updated to account for the unlink. */
630 static forceinline struct avl_tree_node *
631 avl_tree_swap_with_successor(struct avl_tree_node **root_ptr,
632 struct avl_tree_node *X,
633 bool *left_deleted_ret)
635 struct avl_tree_node *Y, *ret;
648 * [ X unlinked, Y returned ]
651 *left_deleted_ret = false;
653 struct avl_tree_node *Q;
665 * A ... => A ... => A ...
674 * [ X unlinked, Q returned ]
679 avl_set_parent(Q->left, Q);
681 avl_set_parent(X->right, Y);
683 *left_deleted_ret = true;
687 avl_set_parent(X->left, Y);
689 Y->parent_balance = X->parent_balance;
690 avl_replace_child(root_ptr, avl_get_parent(X), X, Y);
696 * Removes an item from the specified AVL tree.
699 * Location of the AVL tree's root pointer. Indirection is needed
700 * because the root node may change if the tree needed to be rebalanced
701 * because of the deletion or if @node was the root node.
704 * Pointer to the `struct avl_tree_node' embedded in the item to
705 * remove from the tree.
707 * Note: This function *only* removes the node and rebalances the tree.
708 * It does not free any memory, nor does it do the equivalent of
709 * avl_tree_node_set_unlinked().
712 avl_tree_remove(struct avl_tree_node **root_ptr, struct avl_tree_node *node)
714 struct avl_tree_node *parent;
715 bool left_deleted = false;
717 if (node->left && node->right) {
718 /* @node is fully internal, with two children. Swap it
719 * with its in-order successor (which must exist in the
720 * right subtree of @node and can have, at most, a right
721 * child), then unlink @node. */
722 parent = avl_tree_swap_with_successor(root_ptr, node,
724 /* @parent is now the parent of what was @node's in-order
725 * successor. It cannot be NULL, since @node itself was
726 * an ancestor of its in-order successor.
727 * @left_deleted has been set to %true if @node's
728 * in-order successor was the left child of @parent,
729 * otherwise %false. */
731 struct avl_tree_node *child;
733 /* @node is missing at least one child. Unlink it. Set
734 * @parent to @node's parent, and set @left_deleted to
735 * reflect which child of @parent @node was. Or, if
736 * @node was the root node, simply update the root node
738 child = node->left ? node->left : node->right;
739 parent = avl_get_parent(node);
741 if (node == parent->left) {
742 parent->left = child;
745 parent->right = child;
746 left_deleted = false;
749 avl_set_parent(child, parent);
752 avl_set_parent(child, parent);
758 /* Rebalance the tree. */
761 parent = avl_handle_subtree_shrink(root_ptr, parent,
764 parent = avl_handle_subtree_shrink(root_ptr, parent,