2 * Copyright (C) 2008 Apple Inc. All rights reserved.
4 * Based on Abstract AVL Tree Template v1.5 by Walt Karas
5 * <http://geocities.com/wkaras/gen_cpp/avl_tree.html>.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
17 * its contributors may be used to endorse or promote products derived
18 * from this software without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
21 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
24 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
25 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
27 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 #include "Assertions.h"
36 #include <wtf/FixedArray.h>
40 // Here is the reference class for BSet.
50 // void operator = (bool b);
53 // // Does not have to initialize bits.
56 // // Must return a valid value for index when 0 <= index < maxDepth
57 // ANY_bitref operator [] (unsigned index);
59 // // Set all bits to 1.
62 // // Set all bits to 0.
66 template<unsigned maxDepth>
67 class AVLTreeDefaultBSet {
69 bool& operator[](unsigned i) { ASSERT(i < maxDepth); return m_data[i]; }
70 void set() { for (unsigned i = 0; i < maxDepth; ++i) m_data[i] = true; }
71 void reset() { for (unsigned i = 0; i < maxDepth; ++i) m_data[i] = false; }
74 FixedArray<bool, maxDepth> m_data;
77 // How to determine maxDepth:
78 // d Minimum number of nodes
124 // E.g., if, in a particular instantiation, the maximum number of nodes in a tree instance is 1,000,000, the maximum depth should be 28.
125 // You pick 28 because MN(28) is 832,039, which is less than or equal to 1,000,000, and MN(29) is 1,346,268, which is strictly greater than 1,000,000.
127 template <class Abstractor, unsigned maxDepth = 32, class BSet = AVLTreeDefaultBSet<maxDepth> >
131 typedef typename Abstractor::key key;
132 typedef typename Abstractor::handle handle;
133 typedef typename Abstractor::size size;
139 LESS_EQUAL = EQUAL | LESS,
140 GREATER_EQUAL = EQUAL | GREATER
144 Abstractor& abstractor() { return abs; }
146 inline handle insert(handle h);
148 inline handle search(key k, SearchType st = EQUAL);
149 inline handle search_least();
150 inline handle search_greatest();
152 inline handle remove(key k);
154 inline handle subst(handle new_node);
156 void purge() { abs.root = null(); }
158 bool is_empty() { return abs.root == null(); }
160 AVLTree() { abs.root = null(); }
165 // Initialize depth to invalid value, to indicate iterator is
166 // invalid. (Depth is zero-base.)
167 Iterator() { depth = ~0U; }
169 void start_iter(AVLTree &tree, key k, SearchType st = EQUAL)
171 // Mask of high bit in an int.
172 const int MASK_HIGH_BIT = (int) ~ ((~ (unsigned) 0) >> 1);
174 // Save the tree that we're going to iterate through in a
179 handle h = tree_->abs.root;
189 // Key can be greater than key of starting node.
191 else if (st & GREATER)
192 // Key can be less than key of starting node.
195 // Key must be same as key of starting node.
202 // Equal node was sought and found as starting node.
207 } else if (target_cmp != 0) {
208 if (!((cmp ^ target_cmp) & MASK_HIGH_BIT)) {
209 // cmp and target_cmp are both negative or both positive.
213 h = cmp < 0 ? get_lt(h) : get_gt(h);
221 void start_iter_least(AVLTree &tree)
225 handle h = tree_->abs.root;
231 while (h != null()) {
239 void start_iter_greatest(AVLTree &tree)
243 handle h = tree_->abs.root;
249 while (h != null()) {
262 return depth == 0 ? tree_->abs.root : path_h[depth - 1];
268 handle h = get_gt(**this);
276 } while (branch[depth]);
278 branch[depth] = true;
284 branch[depth] = false;
294 handle h = get_lt(**this);
302 } while (!branch[depth]);
304 branch[depth] = false;
310 branch[depth] = true;
317 void operator++(int) { ++(*this); }
318 void operator--(int) { --(*this); }
322 // Tree being iterated over.
325 // Records a path into the tree. If branch[n] is true, indicates
326 // take greater branch from the nth node in the path, otherwise
327 // take the less branch. branch[0] gives branch from root, and
331 // Zero-based depth of path into tree.
334 // Handles of nodes in path from root to current node (returned by *).
335 handle path_h[maxDepth - 1];
337 int cmp_k_n(key k, handle h) { return tree_->abs.compare_key_node(k, h); }
338 int cmp_n_n(handle h1, handle h2) { return tree_->abs.compare_node_node(h1, h2); }
339 handle get_lt(handle h) { return tree_->abs.get_less(h); }
340 handle get_gt(handle h) { return tree_->abs.get_greater(h); }
341 handle null() { return tree_->abs.null(); }
344 template<typename fwd_iter>
345 bool build(fwd_iter p, size num_nodes)
347 if (num_nodes == 0) {
352 // Gives path to subtree being built. If branch[N] is false, branch
353 // less from the node at depth N, if true branch greater.
356 // If rem[N] is true, then for the current subtree at depth N, it's
357 // greater subtree has one more node than it's less subtree.
360 // Depth of root node of current subtree.
363 // Number of nodes in current subtree.
364 size num_sub = num_nodes;
366 // The algorithm relies on a stack of nodes whose less subtree has
367 // been built, but whose right subtree has not yet been built. The
368 // stack is implemented as linked list. The nodes are linked
369 // together by having the "greater" handle of a node set to the
370 // next node in the list. "less_parent" is the handle of the first
372 handle less_parent = null();
374 // h is root of current subtree, child is one of its children.
378 while (num_sub > 2) {
379 // Subtract one for root of subtree.
381 rem[depth] = !!(num_sub & 1);
382 branch[depth++] = false;
387 // Build a subtree with two nodes, slanting to greater.
388 // I arbitrarily chose to always have the extra node in the
389 // greater subtree when there is an odd number of nodes to
390 // split between the two subtrees.
396 set_lt(child, null());
397 set_gt(child, null());
402 } else { // num_sub == 1
403 // Build a subtree with one node.
415 // We've completed a less subtree.
418 // We've completed a greater subtree, so attach it to
419 // its parent (that is less than it). We pop the parent
420 // off the stack of less parents.
423 less_parent = get_gt(h);
425 // num_sub = 2 * (num_sub - rem[depth]) + rem[depth] + 1
427 num_sub += 1 - rem[depth];
428 if (num_sub & (num_sub - 1))
429 // num_sub is not a power of 2
432 // num_sub is a power of 2
436 if (num_sub == num_nodes)
437 // We've completed the full tree.
440 // The subtree we've completed is the less subtree of the
441 // next node in the sequence.
448 // Put h into stack of less parents.
449 set_gt(h, less_parent);
452 // Proceed to creating greater than subtree of h.
453 branch[depth] = true;
454 num_sub += rem[depth++];
465 friend class Iterator;
467 // Create a class whose sole purpose is to take advantage of
468 // the "empty member" optimization.
469 struct abs_plus_root : public Abstractor {
470 // The handle of the root element in the AVL tree.
477 handle get_lt(handle h) { return abs.get_less(h); }
478 void set_lt(handle h, handle lh) { abs.set_less(h, lh); }
480 handle get_gt(handle h) { return abs.get_greater(h); }
481 void set_gt(handle h, handle gh) { abs.set_greater(h, gh); }
483 int get_bf(handle h) { return abs.get_balance_factor(h); }
484 void set_bf(handle h, int bf) { abs.set_balance_factor(h, bf); }
486 int cmp_k_n(key k, handle h) { return abs.compare_key_node(k, h); }
487 int cmp_n_n(handle h1, handle h2) { return abs.compare_node_node(h1, h2); }
489 handle null() { return abs.null(); }
493 // Balances subtree, returns handle of root node of subtree
495 handle balance(handle bal_h)
499 // Either the "greater than" or the "less than" subtree of
500 // this node has to be 2 levels deeper (or else it wouldn't
503 if (get_bf(bal_h) > 0) {
504 // "Greater than" subtree is deeper.
506 deep_h = get_gt(bal_h);
508 if (get_bf(deep_h) < 0) {
509 handle old_h = bal_h;
510 bal_h = get_lt(deep_h);
512 set_gt(old_h, get_lt(bal_h));
513 set_lt(deep_h, get_gt(bal_h));
514 set_lt(bal_h, old_h);
515 set_gt(bal_h, deep_h);
517 int bf = get_bf(bal_h);
532 set_gt(bal_h, get_lt(deep_h));
533 set_lt(deep_h, bal_h);
534 if (get_bf(deep_h) == 0) {
544 // "Less than" subtree is deeper.
546 deep_h = get_lt(bal_h);
548 if (get_bf(deep_h) > 0) {
549 handle old_h = bal_h;
550 bal_h = get_gt(deep_h);
551 set_lt(old_h, get_gt(bal_h));
552 set_gt(deep_h, get_lt(bal_h));
553 set_gt(bal_h, old_h);
554 set_lt(bal_h, deep_h);
556 int bf = get_bf(bal_h);
571 set_lt(bal_h, get_gt(deep_h));
572 set_gt(deep_h, bal_h);
573 if (get_bf(deep_h) == 0) {
589 template <class Abstractor, unsigned maxDepth, class BSet>
590 inline typename AVLTree<Abstractor, maxDepth, BSet>::handle
591 AVLTree<Abstractor, maxDepth, BSet>::insert(handle h)
597 if (abs.root == null())
600 // Last unbalanced node encountered in search for insertion point.
601 handle unbal = null();
602 // Parent of last unbalanced node.
603 handle parent_unbal = null();
604 // Balance factor of last unbalanced node.
607 // Zero-based depth in tree.
608 unsigned depth = 0, unbal_depth = 0;
610 // Records a path into the tree. If branch[n] is true, indicates
611 // take greater branch from the nth node in the path, otherwise
612 // take the less branch. branch[0] gives branch from root, and
616 handle hh = abs.root;
617 handle parent = null();
621 if (get_bf(hh) != 0) {
623 parent_unbal = parent;
626 cmp = cmp_n_n(h, hh);
631 hh = cmp < 0 ? get_lt(hh) : get_gt(hh);
632 branch[depth++] = cmp > 0;
633 } while (hh != null());
635 // Add node to insert as leaf of tree.
646 cmp = branch[depth++] ? 1 : -1;
647 unbal_bf = get_bf(unbal);
652 hh = cmp < 0 ? get_lt(unbal) : get_gt(unbal);
653 if ((unbal_bf != -2) && (unbal_bf != 2)) {
654 // No rebalancing of tree is necessary.
655 set_bf(unbal, unbal_bf);
662 cmp = branch[depth++] ? 1 : -1;
672 if (unbal != null()) {
673 unbal = balance(unbal);
674 if (parent_unbal == null())
677 depth = unbal_depth - 1;
678 cmp = branch[depth] ? 1 : -1;
680 set_lt(parent_unbal, unbal);
682 set_gt(parent_unbal, unbal);
690 template <class Abstractor, unsigned maxDepth, class BSet>
691 inline typename AVLTree<Abstractor, maxDepth, BSet>::handle
692 AVLTree<Abstractor, maxDepth, BSet>::search(key k, typename AVLTree<Abstractor, maxDepth, BSet>::SearchType st)
694 const int MASK_HIGH_BIT = (int) ~ ((~ (unsigned) 0) >> 1);
697 handle match_h = null();
702 else if (st & GREATER)
707 while (h != null()) {
715 } else if (target_cmp != 0)
716 if (!((cmp ^ target_cmp) & MASK_HIGH_BIT))
717 // cmp and target_cmp are both positive or both negative.
719 h = cmp < 0 ? get_lt(h) : get_gt(h);
725 template <class Abstractor, unsigned maxDepth, class BSet>
726 inline typename AVLTree<Abstractor, maxDepth, BSet>::handle
727 AVLTree<Abstractor, maxDepth, BSet>::search_least()
729 handle h = abs.root, parent = null();
731 while (h != null()) {
739 template <class Abstractor, unsigned maxDepth, class BSet>
740 inline typename AVLTree<Abstractor, maxDepth, BSet>::handle
741 AVLTree<Abstractor, maxDepth, BSet>::search_greatest()
743 handle h = abs.root, parent = null();
745 while (h != null()) {
753 template <class Abstractor, unsigned maxDepth, class BSet>
754 inline typename AVLTree<Abstractor, maxDepth, BSet>::handle
755 AVLTree<Abstractor, maxDepth, BSet>::remove(key k)
757 // Zero-based depth in tree.
758 unsigned depth = 0, rm_depth;
760 // Records a path into the tree. If branch[n] is true, indicates
761 // take greater branch from the nth node in the path, otherwise
762 // take the less branch. branch[0] gives branch from root, and
767 handle parent = null(), child;
768 int cmp, cmp_shortened_sub_with_path = 0;
772 // No node in tree with given key.
776 // Found node to remove.
779 h = cmp < 0 ? get_lt(h) : get_gt(h);
780 branch[depth++] = cmp > 0;
781 cmp_shortened_sub_with_path = cmp;
784 handle parent_rm = parent;
787 // If the node to remove is not a leaf node, we need to get a
788 // leaf node, or a node with a single leaf as its child, to put
789 // in the place of the node to remove. We will get the greatest
790 // node in the less subtree (of the node to remove), or the least
791 // node in the greater subtree. We take the leaf node from the
792 // deeper subtree, if there is one.
796 branch[depth] = false;
800 branch[depth] = true;
805 if (child != null()) {
812 branch[depth] = false;
815 branch[depth] = true;
818 } while (child != null());
821 // Only went through do loop once. Deleted node will be replaced
822 // in the tree structure by one of its immediate children.
823 cmp_shortened_sub_with_path = -cmp;
825 cmp_shortened_sub_with_path = cmp;
827 // Get the handle of the opposite child, which may not be null.
828 child = cmp > 0 ? get_lt(h) : get_gt(h);
831 if (parent == null())
832 // There were only 1 or 2 nodes in this tree.
834 else if (cmp_shortened_sub_with_path < 0)
835 set_lt(parent, child);
837 set_gt(parent, child);
839 // "path" is the parent of the subtree being eliminated or reduced
840 // from a depth of 2 to 1. If "path" is the node to be removed, we
841 // set path to the node we're about to poke into the position of the
842 // node to be removed.
843 handle path = parent == rm ? h : parent;
846 // Poke in the replacement for the node to be removed.
847 set_lt(h, get_lt(rm));
848 set_gt(h, get_gt(rm));
849 set_bf(h, get_bf(rm));
850 if (parent_rm == null())
853 depth = rm_depth - 1;
855 set_gt(parent_rm, h);
857 set_lt(parent_rm, h);
861 if (path != null()) {
862 // Create a temporary linked list from the parent of the path node
868 if (branch[depth++]) {
879 // Climb from the path node to the root node using the linked
880 // list, restoring the tree structure and rebalancing as necessary.
881 bool reduced_depth = true;
883 cmp = cmp_shortened_sub_with_path;
891 if ((bf == -2) || (bf == 2)) {
896 reduced_depth = (bf == 0);
898 if (parent == null())
902 cmp = branch[--depth] ? 1 : -1;
917 template <class Abstractor, unsigned maxDepth, class BSet>
918 inline typename AVLTree<Abstractor, maxDepth, BSet>::handle
919 AVLTree<Abstractor, maxDepth, BSet>::subst(handle new_node)
922 handle parent = null();
925 /* Search for node already in tree with same key. */
928 /* No node in tree with same key as new node. */
930 cmp = cmp_n_n(new_node, h);
932 /* Found the node to substitute new one for. */
936 h = cmp < 0 ? get_lt(h) : get_gt(h);
939 /* Copy tree housekeeping fields from node in tree to new node. */
940 set_lt(new_node, get_lt(h));
941 set_gt(new_node, get_gt(h));
942 set_bf(new_node, get_bf(h));
944 if (parent == null())
945 /* New node is also new root. */
948 /* Make parent point to new node. */
950 set_lt(parent, new_node);
952 set_gt(parent, new_node);