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"
39 // Here is the reference class for BSet.
49 // void operator = (bool b);
52 // // Does not have to initialize bits.
55 // // Must return a valid value for index when 0 <= index < maxDepth
56 // ANY_bitref operator [] (unsigned index);
58 // // Set all bits to 1.
61 // // Set all bits to 0.
65 template<unsigned maxDepth
>
66 class AVLTreeDefaultBSet
{
68 bool& operator[](unsigned i
) { ASSERT(i
< maxDepth
); return m_data
[i
]; }
69 void set() { for (unsigned i
= 0; i
< maxDepth
; ++i
) m_data
[i
] = true; }
70 void reset() { for (unsigned i
= 0; i
< maxDepth
; ++i
) m_data
[i
] = false; }
73 bool m_data
[maxDepth
];
76 // How to determine maxDepth:
77 // d Minimum number of nodes
123 // 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.
124 // 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.
126 template <class Abstractor
, unsigned maxDepth
= 32, class BSet
= AVLTreeDefaultBSet
<maxDepth
> >
130 typedef typename
Abstractor::key key
;
131 typedef typename
Abstractor::handle handle
;
132 typedef typename
Abstractor::size size
;
138 LESS_EQUAL
= EQUAL
| LESS
,
139 GREATER_EQUAL
= EQUAL
| GREATER
143 Abstractor
& abstractor() { return abs
; }
145 inline handle
insert(handle h
);
147 inline handle
search(key k
, SearchType st
= EQUAL
);
148 inline handle
search_least();
149 inline handle
search_greatest();
151 inline handle
remove(key k
);
153 inline handle
subst(handle new_node
);
155 void purge() { abs
.root
= null(); }
157 bool is_empty() { return abs
.root
== null(); }
159 AVLTree() { abs
.root
= null(); }
164 // Initialize depth to invalid value, to indicate iterator is
165 // invalid. (Depth is zero-base.)
166 Iterator() { depth
= ~0U; }
168 void start_iter(AVLTree
&tree
, key k
, SearchType st
= EQUAL
)
170 // Mask of high bit in an int.
171 const int MASK_HIGH_BIT
= (int) ~ ((~ (unsigned) 0) >> 1);
173 // Save the tree that we're going to iterate through in a
178 handle h
= tree_
->abs
.root
;
188 // Key can be greater than key of starting node.
190 else if (st
& GREATER
)
191 // Key can be less than key of starting node.
194 // Key must be same as key of starting node.
201 // Equal node was sought and found as starting node.
206 } else if (target_cmp
!= 0) {
207 if (!((cmp
^ target_cmp
) & MASK_HIGH_BIT
)) {
208 // cmp and target_cmp are both negative or both positive.
212 h
= cmp
< 0 ? get_lt(h
) : get_gt(h
);
220 void start_iter_least(AVLTree
&tree
)
224 handle h
= tree_
->abs
.root
;
230 while (h
!= null()) {
238 void start_iter_greatest(AVLTree
&tree
)
242 handle h
= tree_
->abs
.root
;
248 while (h
!= null()) {
261 return depth
== 0 ? tree_
->abs
.root
: path_h
[depth
- 1];
267 handle h
= get_gt(**this);
275 } while (branch
[depth
]);
277 branch
[depth
] = true;
283 branch
[depth
] = false;
293 handle h
= get_lt(**this);
301 } while (!branch
[depth
]);
303 branch
[depth
] = false;
309 branch
[depth
] = true;
316 void operator++(int) { ++(*this); }
317 void operator--(int) { --(*this); }
321 // Tree being iterated over.
324 // Records a path into the tree. If branch[n] is true, indicates
325 // take greater branch from the nth node in the path, otherwise
326 // take the less branch. branch[0] gives branch from root, and
330 // Zero-based depth of path into tree.
333 // Handles of nodes in path from root to current node (returned by *).
334 handle path_h
[maxDepth
- 1];
336 int cmp_k_n(key k
, handle h
) { return tree_
->abs
.compare_key_node(k
, h
); }
337 int cmp_n_n(handle h1
, handle h2
) { return tree_
->abs
.compare_node_node(h1
, h2
); }
338 handle
get_lt(handle h
) { return tree_
->abs
.get_less(h
); }
339 handle
get_gt(handle h
) { return tree_
->abs
.get_greater(h
); }
340 handle
null() { return tree_
->abs
.null(); }
343 template<typename fwd_iter
>
344 bool build(fwd_iter p
, size num_nodes
)
346 if (num_nodes
== 0) {
351 // Gives path to subtree being built. If branch[N] is false, branch
352 // less from the node at depth N, if true branch greater.
355 // If rem[N] is true, then for the current subtree at depth N, it's
356 // greater subtree has one more node than it's less subtree.
359 // Depth of root node of current subtree.
362 // Number of nodes in current subtree.
363 size num_sub
= num_nodes
;
365 // The algorithm relies on a stack of nodes whose less subtree has
366 // been built, but whose right subtree has not yet been built. The
367 // stack is implemented as linked list. The nodes are linked
368 // together by having the "greater" handle of a node set to the
369 // next node in the list. "less_parent" is the handle of the first
371 handle less_parent
= null();
373 // h is root of current subtree, child is one of its children.
377 while (num_sub
> 2) {
378 // Subtract one for root of subtree.
380 rem
[depth
] = !!(num_sub
& 1);
381 branch
[depth
++] = false;
386 // Build a subtree with two nodes, slanting to greater.
387 // I arbitrarily chose to always have the extra node in the
388 // greater subtree when there is an odd number of nodes to
389 // split between the two subtrees.
395 set_lt(child
, null());
396 set_gt(child
, null());
401 } else { // num_sub == 1
402 // Build a subtree with one node.
414 // We've completed a less subtree.
417 // We've completed a greater subtree, so attach it to
418 // its parent (that is less than it). We pop the parent
419 // off the stack of less parents.
422 less_parent
= get_gt(h
);
424 // num_sub = 2 * (num_sub - rem[depth]) + rem[depth] + 1
426 num_sub
+= 1 - rem
[depth
];
427 if (num_sub
& (num_sub
- 1))
428 // num_sub is not a power of 2
431 // num_sub is a power of 2
435 if (num_sub
== num_nodes
)
436 // We've completed the full tree.
439 // The subtree we've completed is the less subtree of the
440 // next node in the sequence.
447 // Put h into stack of less parents.
448 set_gt(h
, less_parent
);
451 // Proceed to creating greater than subtree of h.
452 branch
[depth
] = true;
453 num_sub
+= rem
[depth
++];
464 friend class Iterator
;
466 // Create a class whose sole purpose is to take advantage of
467 // the "empty member" optimization.
468 struct abs_plus_root
: public Abstractor
{
469 // The handle of the root element in the AVL tree.
476 handle
get_lt(handle h
) { return abs
.get_less(h
); }
477 void set_lt(handle h
, handle lh
) { abs
.set_less(h
, lh
); }
479 handle
get_gt(handle h
) { return abs
.get_greater(h
); }
480 void set_gt(handle h
, handle gh
) { abs
.set_greater(h
, gh
); }
482 int get_bf(handle h
) { return abs
.get_balance_factor(h
); }
483 void set_bf(handle h
, int bf
) { abs
.set_balance_factor(h
, bf
); }
485 int cmp_k_n(key k
, handle h
) { return abs
.compare_key_node(k
, h
); }
486 int cmp_n_n(handle h1
, handle h2
) { return abs
.compare_node_node(h1
, h2
); }
488 handle
null() { return abs
.null(); }
492 // Balances subtree, returns handle of root node of subtree
494 handle
balance(handle bal_h
)
498 // Either the "greater than" or the "less than" subtree of
499 // this node has to be 2 levels deeper (or else it wouldn't
502 if (get_bf(bal_h
) > 0) {
503 // "Greater than" subtree is deeper.
505 deep_h
= get_gt(bal_h
);
507 if (get_bf(deep_h
) < 0) {
508 handle old_h
= bal_h
;
509 bal_h
= get_lt(deep_h
);
511 set_gt(old_h
, get_lt(bal_h
));
512 set_lt(deep_h
, get_gt(bal_h
));
513 set_lt(bal_h
, old_h
);
514 set_gt(bal_h
, deep_h
);
516 int bf
= get_bf(bal_h
);
531 set_gt(bal_h
, get_lt(deep_h
));
532 set_lt(deep_h
, bal_h
);
533 if (get_bf(deep_h
) == 0) {
543 // "Less than" subtree is deeper.
545 deep_h
= get_lt(bal_h
);
547 if (get_bf(deep_h
) > 0) {
548 handle old_h
= bal_h
;
549 bal_h
= get_gt(deep_h
);
550 set_lt(old_h
, get_gt(bal_h
));
551 set_gt(deep_h
, get_lt(bal_h
));
552 set_gt(bal_h
, old_h
);
553 set_lt(bal_h
, deep_h
);
555 int bf
= get_bf(bal_h
);
570 set_lt(bal_h
, get_gt(deep_h
));
571 set_gt(deep_h
, bal_h
);
572 if (get_bf(deep_h
) == 0) {
588 template <class Abstractor
, unsigned maxDepth
, class BSet
>
589 inline typename AVLTree
<Abstractor
, maxDepth
, BSet
>::handle
590 AVLTree
<Abstractor
, maxDepth
, BSet
>::insert(handle h
)
596 if (abs
.root
== null())
599 // Last unbalanced node encountered in search for insertion point.
600 handle unbal
= null();
601 // Parent of last unbalanced node.
602 handle parent_unbal
= null();
603 // Balance factor of last unbalanced node.
606 // Zero-based depth in tree.
607 unsigned depth
= 0, unbal_depth
= 0;
609 // Records a path into the tree. If branch[n] is true, indicates
610 // take greater branch from the nth node in the path, otherwise
611 // take the less branch. branch[0] gives branch from root, and
615 handle hh
= abs
.root
;
616 handle parent
= null();
620 if (get_bf(hh
) != 0) {
622 parent_unbal
= parent
;
625 cmp
= cmp_n_n(h
, hh
);
630 hh
= cmp
< 0 ? get_lt(hh
) : get_gt(hh
);
631 branch
[depth
++] = cmp
> 0;
632 } while (hh
!= null());
634 // Add node to insert as leaf of tree.
645 cmp
= branch
[depth
++] ? 1 : -1;
646 unbal_bf
= get_bf(unbal
);
651 hh
= cmp
< 0 ? get_lt(unbal
) : get_gt(unbal
);
652 if ((unbal_bf
!= -2) && (unbal_bf
!= 2)) {
653 // No rebalancing of tree is necessary.
654 set_bf(unbal
, unbal_bf
);
661 cmp
= branch
[depth
++] ? 1 : -1;
671 if (unbal
!= null()) {
672 unbal
= balance(unbal
);
673 if (parent_unbal
== null())
676 depth
= unbal_depth
- 1;
677 cmp
= branch
[depth
] ? 1 : -1;
679 set_lt(parent_unbal
, unbal
);
681 set_gt(parent_unbal
, unbal
);
689 template <class Abstractor
, unsigned maxDepth
, class BSet
>
690 inline typename AVLTree
<Abstractor
, maxDepth
, BSet
>::handle
691 AVLTree
<Abstractor
, maxDepth
, BSet
>::search(key k
, typename AVLTree
<Abstractor
, maxDepth
, BSet
>::SearchType st
)
693 const int MASK_HIGH_BIT
= (int) ~ ((~ (unsigned) 0) >> 1);
696 handle match_h
= null();
701 else if (st
& GREATER
)
706 while (h
!= null()) {
714 } else if (target_cmp
!= 0)
715 if (!((cmp
^ target_cmp
) & MASK_HIGH_BIT
))
716 // cmp and target_cmp are both positive or both negative.
718 h
= cmp
< 0 ? get_lt(h
) : get_gt(h
);
724 template <class Abstractor
, unsigned maxDepth
, class BSet
>
725 inline typename AVLTree
<Abstractor
, maxDepth
, BSet
>::handle
726 AVLTree
<Abstractor
, maxDepth
, BSet
>::search_least()
728 handle h
= abs
.root
, parent
= null();
730 while (h
!= null()) {
738 template <class Abstractor
, unsigned maxDepth
, class BSet
>
739 inline typename AVLTree
<Abstractor
, maxDepth
, BSet
>::handle
740 AVLTree
<Abstractor
, maxDepth
, BSet
>::search_greatest()
742 handle h
= abs
.root
, parent
= null();
744 while (h
!= null()) {
752 template <class Abstractor
, unsigned maxDepth
, class BSet
>
753 inline typename AVLTree
<Abstractor
, maxDepth
, BSet
>::handle
754 AVLTree
<Abstractor
, maxDepth
, BSet
>::remove(key k
)
756 // Zero-based depth in tree.
757 unsigned depth
= 0, rm_depth
;
759 // Records a path into the tree. If branch[n] is true, indicates
760 // take greater branch from the nth node in the path, otherwise
761 // take the less branch. branch[0] gives branch from root, and
766 handle parent
= null(), child
;
767 int cmp
, cmp_shortened_sub_with_path
= 0;
771 // No node in tree with given key.
775 // Found node to remove.
778 h
= cmp
< 0 ? get_lt(h
) : get_gt(h
);
779 branch
[depth
++] = cmp
> 0;
780 cmp_shortened_sub_with_path
= cmp
;
783 handle parent_rm
= parent
;
786 // If the node to remove is not a leaf node, we need to get a
787 // leaf node, or a node with a single leaf as its child, to put
788 // in the place of the node to remove. We will get the greatest
789 // node in the less subtree (of the node to remove), or the least
790 // node in the greater subtree. We take the leaf node from the
791 // deeper subtree, if there is one.
795 branch
[depth
] = false;
799 branch
[depth
] = true;
804 if (child
!= null()) {
811 branch
[depth
] = false;
814 branch
[depth
] = true;
817 } while (child
!= null());
820 // Only went through do loop once. Deleted node will be replaced
821 // in the tree structure by one of its immediate children.
822 cmp_shortened_sub_with_path
= -cmp
;
824 cmp_shortened_sub_with_path
= cmp
;
826 // Get the handle of the opposite child, which may not be null.
827 child
= cmp
> 0 ? get_lt(h
) : get_gt(h
);
830 if (parent
== null())
831 // There were only 1 or 2 nodes in this tree.
833 else if (cmp_shortened_sub_with_path
< 0)
834 set_lt(parent
, child
);
836 set_gt(parent
, child
);
838 // "path" is the parent of the subtree being eliminated or reduced
839 // from a depth of 2 to 1. If "path" is the node to be removed, we
840 // set path to the node we're about to poke into the position of the
841 // node to be removed.
842 handle path
= parent
== rm
? h
: parent
;
845 // Poke in the replacement for the node to be removed.
846 set_lt(h
, get_lt(rm
));
847 set_gt(h
, get_gt(rm
));
848 set_bf(h
, get_bf(rm
));
849 if (parent_rm
== null())
852 depth
= rm_depth
- 1;
854 set_gt(parent_rm
, h
);
856 set_lt(parent_rm
, h
);
860 if (path
!= null()) {
861 // Create a temporary linked list from the parent of the path node
867 if (branch
[depth
++]) {
878 // Climb from the path node to the root node using the linked
879 // list, restoring the tree structure and rebalancing as necessary.
880 bool reduced_depth
= true;
882 cmp
= cmp_shortened_sub_with_path
;
890 if ((bf
== -2) || (bf
== 2)) {
895 reduced_depth
= (bf
== 0);
897 if (parent
== null())
901 cmp
= branch
[--depth
] ? 1 : -1;
916 template <class Abstractor
, unsigned maxDepth
, class BSet
>
917 inline typename AVLTree
<Abstractor
, maxDepth
, BSet
>::handle
918 AVLTree
<Abstractor
, maxDepth
, BSet
>::subst(handle new_node
)
921 handle parent
= null();
924 /* Search for node already in tree with same key. */
927 /* No node in tree with same key as new node. */
929 cmp
= cmp_n_n(new_node
, h
);
931 /* Found the node to substitute new one for. */
935 h
= cmp
< 0 ? get_lt(h
) : get_gt(h
);
938 /* Copy tree housekeeping fields from node in tree to new node. */
939 set_lt(new_node
, get_lt(h
));
940 set_gt(new_node
, get_gt(h
));
941 set_bf(new_node
, get_bf(h
));
943 if (parent
== null())
944 /* New node is also new root. */
947 /* Make parent point to new node. */
949 set_lt(parent
, new_node
);
951 set_gt(parent
, new_node
);