2 * Copyright 2001 Adrian Thurston <thurston@cs.queensu.ca>
5 /* This file is part of Aapl.
7 * Aapl is free software; you can redistribute it and/or modify it under the
8 * terms of the GNU Lesser General Public License as published by the Free
9 * Software Foundation; either version 2.1 of the License, or (at your option)
12 * Aapl is distributed in the hope that it will be useful, but WITHOUT ANY
13 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with Aapl; if not, write to the Free Software Foundation, Inc., 59
19 * Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 /* This header is not wrapped in ifndef becuase it is not intended to
23 * be included by the user. */
32 /* This is used by AvlTree, AvlMel and AvlMelKey so it
33 * must be protected by global ifdefs. */
34 #ifndef __AAPL_AVLI_EL__
35 #define __AAPL_AVLI_EL__
38 * \brief Tree element properties for linked AVL trees.
40 * AvliTreeEl needs to be inherited by classes that intend to be element in an
43 template<class SubClassEl> struct AvliTreeEl
46 * \brief Tree pointers connecting element in a tree.
48 SubClassEl *left, *right, *parent;
51 * \brief Linked list pointers.
53 SubClassEl *prev, *next;
56 * \brief Height of the tree rooted at this element.
58 * Height is required by the AVL balancing algorithm.
62 #endif /* __AAPL_AVLI_EL__ */
64 #else /* not WALKABLE */
66 /* This is used by All the non walkable trees so it must be
67 * protected by a global ifdef. */
68 #ifndef __AAPL_AVL_EL__
69 #define __AAPL_AVL_EL__
71 * \brief Tree element properties for linked AVL trees.
73 * AvlTreeEl needs to be inherited by classes that intend to be element in an
76 template<class SubClassEl> struct AvlTreeEl
79 * \brief Tree pointers connecting element in a tree.
81 SubClassEl *left, *right, *parent;
84 * \brief Height of the tree rooted at this element.
86 * Height is required by the AVL balancing algorithm.
90 #endif /* __AAPL_AVL_EL__ */
91 #endif /* def WALKABLE */
94 #if defined( AVLTREE_MAP )
99 * \brief Tree element for AvliMap
101 * Stores the key and value pair.
103 template <class Key, class Value> struct AvliMapEl :
104 public AvliTreeEl< AvliMapEl<Key, Value> >
106 AvliMapEl(const Key &key)
108 AvliMapEl(const Key &key, const Value &value)
109 : key(key), value(value) { }
111 const Key &getKey() const { return key; }
113 /** \brief The key. */
116 /** \brief The value. */
119 #else /* not WALKABLE */
122 * \brief Tree element for AvlMap
124 * Stores the key and value pair.
126 template <class Key, class Value> struct AvlMapEl :
127 public AvlTreeEl< AvlMapEl<Key, Value> >
129 AvlMapEl(const Key &key)
131 AvlMapEl(const Key &key, const Value &value)
132 : key(key), value(value) { }
134 const Key &getKey() const { return key; }
136 /** \brief The key. */
139 /** \brief The value. */
142 #endif /* def WALKABLE */
144 #elif defined( AVLTREE_SET )
148 * \brief Tree element for AvliSet
152 template <class Key> struct AvliSetEl :
153 public AvliTreeEl< AvliSetEl<Key> >
155 AvliSetEl(const Key &key) : key(key) { }
157 const Key &getKey() const { return key; }
159 /** \brief The key. */
162 #else /* not WALKABLE */
164 * \brief Tree element for AvlSet
168 template <class Key> struct AvlSetEl :
169 public AvlTreeEl< AvlSetEl<Key> >
171 AvlSetEl(const Key &key) : key(key) { }
173 const Key &getKey() const { return key; }
175 /** \brief The key. */
178 #endif /* def WALKABLE */
180 #endif /* AVLTREE_SET */
182 /* Common AvlTree Class */
183 template < AVLMEL_CLASSDEF > class AvlTree
184 #if !defined( AVL_KEYLESS ) && defined ( WALKABLE )
185 : public Compare, public BASELIST
186 #elif !defined( AVL_KEYLESS )
188 #elif defined( WALKABLE )
194 * \brief Create an empty tree.
197 AvlTree() : root(0), treeSize(0) { }
199 AvlTree() : root(0), head(0), tail(0), treeSize(0) { }
203 * \brief Perform a deep copy of the tree.
205 * Each element is duplicated for the new tree. Copy constructors are used
206 * to create the new elements.
208 AvlTree(const AvlTree &other);
210 #if defined( AVLTREE_MAP ) || defined( AVLTREE_SET )
212 * \brief Clear the contents of the tree.
214 * All element are deleted.
216 ~AvlTree() { empty(); }
219 * \brief Perform a deep copy of the tree.
221 * Each element is duplicated for the new tree. Copy constructors are used
222 * to create the new element. If this tree contains items, they are first
225 * \returns A reference to this.
227 AvlTree &operator=( const AvlTree &tree );
230 * \brief Transfer the elements of another tree into this.
232 * First deletes all elements in this tree.
234 void transfer( AvlTree &tree );
237 * \brief Abandon all elements in the tree.
239 * Tree elements are not deleted.
244 * \brief Perform a deep copy of the tree.
246 * Each element is duplicated for the new tree. Copy constructors are used
247 * to create the new element. If this tree contains items, they are
250 * \returns A reference to this.
252 AvlTree &operator=( const AvlTree &tree );
255 * \brief Transfer the elements of another tree into this.
257 * All elements in this tree are abandoned first.
259 void transfer( AvlTree &tree );
263 /* Insert a element into the tree. */
264 Element *insert( Element *element, Element **lastFound = 0 );
267 /* Find a element in the tree. Returns the element if
268 * element exists, false otherwise. */
269 Element *find( const Element *element ) const;
272 Element *insert( const Key &key, Element **lastFound = 0 );
275 Element *insert( const Key &key, const Value &val,
276 Element **lastFound = 0 );
279 /* Find a element in the tree. Returns the element if
280 * key exists, false otherwise. */
281 Element *find( const Key &key ) const;
283 /* Detach a element from the tree. */
284 Element *detach( const Key &key );
286 /* Detach and delete a element from the tree. */
287 bool remove( const Key &key );
288 #endif /* AVL_BASIC */
289 #endif /* AVL_KEYLESS */
291 /* Detach a element from the tree. */
292 Element *detach( Element *element );
294 /* Detach and delete a element from the tree. */
295 void remove( Element *element );
297 /* Free all memory used by tree. */
300 /* Abandon all element in the tree. Does not delete element. */
303 /** Root element of the tree. */
307 Element *head, *tail;
310 /** The number of element in the tree. */
313 /** \brief Return the number of elements in the tree. */
314 long length() const { return treeSize; }
316 /** \brief Return the number of elements in the tree. */
317 long size() const { return treeSize; }
319 /* Various classes for setting the iterator */
321 struct IterFirst { IterFirst( const AvlTree &t ) : t(t) { } const AvlTree &t; };
322 struct IterLast { IterLast( const AvlTree &t ) : t(t) { } const AvlTree &t; };
323 struct IterNext { IterNext( const Iter &i ) : i(i) { } const Iter &i; };
324 struct IterPrev { IterPrev( const Iter &i ) : i(i) { } const Iter &i; };
328 * \brief Avl Tree Iterator.
333 /* Default construct. */
336 /* Construct from an avl tree and iterator-setting classes. */
337 Iter( const AvlTree &t ) : ptr(t.head) { }
338 Iter( const IterFirst &af ) : ptr(af.t.head) { }
339 Iter( const IterLast &al ) : ptr(al.t.tail) { }
340 Iter( const IterNext &an ) : ptr(findNext(an.i.ptr)) { }
341 Iter( const IterPrev &ap ) : ptr(findPrev(ap.i.ptr)) { }
343 /* Assign from a tree and iterator-setting classes. */
344 Iter &operator=( const AvlTree &tree ) { ptr = tree.head; return *this; }
345 Iter &operator=( const IterFirst &af ) { ptr = af.t.head; return *this; }
346 Iter &operator=( const IterLast &al ) { ptr = al.t.tail; return *this; }
347 Iter &operator=( const IterNext &an ) { ptr = findNext(an.i.ptr); return *this; }
348 Iter &operator=( const IterPrev &ap ) { ptr = findPrev(ap.i.ptr); return *this; }
350 /** \brief Less than end? */
351 bool lte() const { return ptr != 0; }
353 /** \brief At end? */
354 bool end() const { return ptr == 0; }
356 /** \brief Greater than beginning? */
357 bool gtb() const { return ptr != 0; }
359 /** \brief At beginning? */
360 bool beg() const { return ptr == 0; }
362 /** \brief At first element? */
363 bool first() const { return ptr && ptr->BASE_EL(prev) == 0; }
365 /** \brief At last element? */
366 bool last() const { return ptr && ptr->BASE_EL(next) == 0; }
368 /** \brief Implicit cast to Element*. */
369 operator Element*() const { return ptr; }
371 /** \brief Dereference operator returns Element&. */
372 Element &operator *() const { return *ptr; }
374 /** \brief Arrow operator returns Element*. */
375 Element *operator->() const { return ptr; }
377 /** \brief Move to next item. */
378 inline Element *operator++();
380 /** \brief Move to next item. */
381 inline Element *operator++(int);
383 /** \brief Move to next item. */
384 inline Element *increment();
386 /** \brief Move to previous item. */
387 inline Element *operator--();
389 /** \brief Move to previous item. */
390 inline Element *operator--(int);
392 /** \brief Move to previous item. */
393 inline Element *decrement();
395 /** \brief Return the next item. Does not modify this. */
396 IterNext next() const { return IterNext( *this ); }
398 /** \brief Return the previous item. Does not modify this. */
399 IterPrev prev() const { return IterPrev( *this ); }
402 static Element *findPrev( Element *element ) { return element->BASE_EL(prev); }
403 static Element *findNext( Element *element ) { return element->BASE_EL(next); }
407 /** \brief The iterator is simply a pointer. */
414 * \brief Avl Tree Iterator.
419 /* Default construct. */
420 Iter() : ptr(0), tree(0) { }
422 /* Construct from a tree and iterator-setting classes. */
423 Iter( const AvlTree &t ) : ptr(t.head), tree(&t) { }
424 Iter( const IterFirst &af ) : ptr(af.t.head), tree(&af.t) { }
425 Iter( const IterLast &al ) : ptr(al.t.tail), tree(&al.t) { }
426 Iter( const IterNext &an ) : ptr(findNext(an.i.ptr)), tree(an.i.tree) { }
427 Iter( const IterPrev &ap ) : ptr(findPrev(ap.i.ptr)), tree(ap.i.tree) { }
429 /* Assign from a tree and iterator-setting classes. */
430 Iter &operator=( const AvlTree &t )
431 { ptr = t.head; tree = &t; return *this; }
432 Iter &operator=( const IterFirst &af )
433 { ptr = af.t.head; tree = &af.t; return *this; }
434 Iter &operator=( const IterLast &al )
435 { ptr = al.t.tail; tree = &al.t; return *this; }
436 Iter &operator=( const IterNext &an )
437 { ptr = findNext(an.i.ptr); tree = an.i.tree; return *this; }
438 Iter &operator=( const IterPrev &ap )
439 { ptr = findPrev(ap.i.ptr); tree = ap.i.tree; return *this; }
441 /** \brief Less than end? */
442 bool lte() const { return ptr != 0; }
444 /** \brief At end? */
445 bool end() const { return ptr == 0; }
447 /** \brief Greater than beginning? */
448 bool gtb() const { return ptr != 0; }
450 /** \brief At beginning? */
451 bool beg() const { return ptr == 0; }
453 /** \brief At first element? */
454 bool first() const { return ptr && ptr == tree->head; }
456 /** \brief At last element? */
457 bool last() const { return ptr && ptr == tree->tail; }
459 /** \brief Implicit cast to Element*. */
460 operator Element*() const { return ptr; }
462 /** \brief Dereference operator returns Element&. */
463 Element &operator *() const { return *ptr; }
465 /** \brief Arrow operator returns Element*. */
466 Element *operator->() const { return ptr; }
468 /** \brief Move to next item. */
469 inline Element *operator++();
471 /** \brief Move to next item. */
472 inline Element *operator++(int);
474 /** \brief Move to next item. */
475 inline Element *increment();
477 /** \brief Move to previous item. */
478 inline Element *operator--();
480 /** \brief Move to previous item. */
481 inline Element *operator--(int);
483 /** \brief Move to previous item. */
484 inline Element *decrement();
486 /** \brief Return the next item. Does not modify this. */
487 IterNext next() const { return IterNext( *this ); }
489 /** \brief Return the previous item. Does not modify this. */
490 IterPrev prev() const { return IterPrev( *this ); }
493 static Element *findPrev( Element *element );
494 static Element *findNext( Element *element );
497 /** \brief The iterator is simply a pointer. */
500 /* The list is not walkable so we need to keep a pointerto the tree
501 * so we can test against head and tail in O(1) time. */
506 /** \brief Return first element. */
507 IterFirst first() { return IterFirst( *this ); }
509 /** \brief Return last element. */
510 IterLast last() { return IterLast( *this ); }
513 /* Recursive worker for the copy constructor. */
514 Element *copyBranch( Element *element );
516 /* Recursively delete element in the tree. */
517 void deleteChildrenOf(Element *n);
519 /* rebalance the tree beginning at the leaf whose
520 * grandparent is unbalanced. */
521 Element *rebalance(Element *start);
523 /* Move up the tree from a given element, recalculating the heights. */
524 void recalcHeights(Element *start);
526 /* Move up the tree and find the first element whose
527 * grand-parent is unbalanced. */
528 Element *findFirstUnbalGP(Element *start);
530 /* Move up the tree and find the first element which is unbalanced. */
531 Element *findFirstUnbalEl(Element *start);
533 /* Replace a element in the tree with another element not in the tree. */
534 void replaceEl(Element *element, Element *replacement);
536 /* Remove a element from the tree and put another (normally a child of element)
538 void removeEl(Element *element, Element *filler);
540 /* Once an insertion point is found at a leaf then do the insert. */
541 void attachRebal( Element *element, Element *parentEl, Element *lastLess );
544 /* Copy constructor. New up each item. */
545 template <AVLMEL_TEMPDEF> AvlTree<AVLMEL_TEMPUSE>::
546 AvlTree(const AvlTree<AVLMEL_TEMPUSE> &other)
549 /* Make an empty list, copyBranch will fill in the details for us. */
553 treeSize = other.treeSize;
561 /* If there is a root, copy the tree. */
562 if ( other.root != 0 )
563 root = copyBranch( other.root );
566 #if defined( AVLTREE_MAP ) || defined( AVLTREE_SET )
568 /* Assignment does deep copy. */
569 template <AVLMEL_TEMPDEF> AvlTree<AVLMEL_TEMPUSE> &AvlTree<AVLMEL_TEMPUSE>::
570 operator=( const AvlTree &other )
572 /* Clear the tree first. */
575 /* Reset the list pointers, the tree copy will fill in the list for us. */
583 /* Copy the entire tree. */
584 treeSize = other.treeSize;
586 if ( other.root != 0 )
587 root = copyBranch( other.root );
591 template <AVLMEL_TEMPDEF> void AvlTree<AVLMEL_TEMPUSE>::
592 transfer(AvlTree<AVLMEL_TEMPUSE> &other)
594 /* Clear the tree first. */
597 treeSize = other.treeSize;
601 BASELIST::shallowCopy( other );
610 #else /* ! AVLTREE_MAP && ! AVLTREE_SET */
612 /* Assignment does deep copy. This version does not clear the tree first. */
613 template <AVLMEL_TEMPDEF> AvlTree<AVLMEL_TEMPUSE> &AvlTree<AVLMEL_TEMPUSE>::
614 operator=( const AvlTree &other )
616 /* Reset the list pointers, the tree copy will fill in the list for us. */
624 /* Copy the entire tree. */
625 treeSize = other.treeSize;
627 if ( other.root != 0 )
628 root = copyBranch( other.root );
632 template <AVLMEL_TEMPDEF> void AvlTree<AVLMEL_TEMPUSE>::
633 transfer(AvlTree<AVLMEL_TEMPUSE> &other)
635 treeSize = other.treeSize;
639 BASELIST::shallowCopy( other );
651 * Iterator operators.
655 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::Iter::
658 return ptr = findNext( ptr );
662 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::Iter::
666 ptr = findNext( ptr );
671 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::Iter::
674 return ptr = findNext( ptr );
678 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::Iter::
681 return ptr = findPrev( ptr );
685 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::Iter::
689 ptr = findPrev( ptr );
694 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::Iter::
697 return ptr = findPrev( ptr );
702 /* Move ahead one. */
703 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::Iter::
704 findNext( Element *element )
706 /* Try to go right once then infinite left. */
707 if ( element->BASE_EL(right) != 0 ) {
708 element = element->BASE_EL(right);
709 while ( element->BASE_EL(left) != 0 )
710 element = element->BASE_EL(left);
713 /* Go up to parent until we were just a left child. */
715 Element *last = element;
716 element = element->BASE_EL(parent);
717 if ( element == 0 || element->BASE_EL(left) == last )
725 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::Iter::
726 findPrev( Element *element )
728 /* Try to go left once then infinite right. */
729 if ( element->BASE_EL(left) != 0 ) {
730 element = element->BASE_EL(left);
731 while ( element->BASE_EL(right) != 0 )
732 element = element->BASE_EL(right);
735 /* Go up to parent until we were just a left child. */
737 Element *last = element;
738 element = element->BASE_EL(parent);
739 if ( element == 0 || element->BASE_EL(right) == last )
749 /* Recursive worker for tree copying. */
750 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::
751 copyBranch( Element *element )
753 /* Duplicate element. Either the base element's copy constructor or defaul
754 * constructor will get called. Both will suffice for initting the
755 * pointers to null when they need to be. */
756 Element *retVal = new Element(*element);
758 /* If the left tree is there, copy it. */
759 if ( retVal->BASE_EL(left) ) {
760 retVal->BASE_EL(left) = copyBranch(retVal->BASE_EL(left));
761 retVal->BASE_EL(left)->BASE_EL(parent) = retVal;
765 BASELIST::addAfter( BASELIST::tail, retVal );
772 /* If the right tree is there, copy it. */
773 if ( retVal->BASE_EL(right) ) {
774 retVal->BASE_EL(right) = copyBranch(retVal->BASE_EL(right));
775 retVal->BASE_EL(right)->BASE_EL(parent) = retVal;
780 /* Once an insertion position is found, attach a element to the tree. */
781 template <AVLMEL_TEMPDEF> void AvlTree<AVLMEL_TEMPUSE>::
782 attachRebal( Element *element, Element *parentEl, Element *lastLess )
784 /* Increment the number of element in the tree. */
787 /* Set element's parent. */
788 element->BASE_EL(parent) = parentEl;
790 /* New element always starts as a leaf with height 1. */
791 element->BASE_EL(left) = 0;
792 element->BASE_EL(right) = 0;
793 element->BASE_EL(height) = 1;
795 /* Are we inserting in the tree somewhere? */
796 if ( parentEl != 0 ) {
797 /* We have a parent so we are somewhere in the tree. If the parent
798 * equals lastLess, then the last traversal in the insertion went
799 * left, otherwise it went right. */
800 if ( lastLess == parentEl ) {
801 parentEl->BASE_EL(left) = element;
803 BASELIST::addBefore( parentEl, element );
807 parentEl->BASE_EL(right) = element;
809 BASELIST::addAfter( parentEl, element );
814 /* Maintain the first and last pointers. */
815 if ( head->BASE_EL(left) == element )
818 /* Maintain the first and last pointers. */
819 if ( tail->BASE_EL(right) == element )
824 /* No parent element so we are inserting the root. */
827 BASELIST::addAfter( BASELIST::tail, element );
829 head = tail = element;
834 /* Recalculate the heights. */
835 recalcHeights(parentEl);
837 /* Find the first unbalance. */
838 Element *ub = findFirstUnbalGP(element);
843 /* We assert that after this single rotation the
844 * tree is now properly balanced. */
852 * \brief Insert an existing element into the tree.
854 * If the insert succeeds and lastFound is given then it is set to the element
855 * inserted. If the insert fails then lastFound is set to the existing element in
856 * the tree that has the same key as element. If the element's avl pointers are
857 * already in use then undefined behaviour results.
859 * \returns The element inserted upon success, null upon failure.
861 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::
862 insert( Element *element, Element **lastFound )
865 Element *curEl = root, *parentEl = 0;
866 Element *lastLess = 0;
870 /* We are at an external element and did not find the key we were
871 * looking for. Attach underneath the leaf and rebalance. */
872 attachRebal( element, parentEl, lastLess );
874 if ( lastFound != 0 )
875 *lastFound = element;
880 keyRelation = compare( *element, *curEl );
882 keyRelation = compare( element->BASEKEY(getKey()),
883 curEl->BASEKEY(getKey()) );
887 if ( keyRelation < 0 ) {
888 parentEl = lastLess = curEl;
889 curEl = curEl->BASE_EL(left);
891 /* Do we go right? */
892 else if ( keyRelation > 0 ) {
894 curEl = curEl->BASE_EL(right);
896 /* We have hit the target. */
898 if ( lastFound != 0 )
908 * \brief Find a element in the tree with the given key.
910 * \returns The element if key exists, null if the key does not exist.
912 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::
913 find( const Element *element ) const
915 Element *curEl = root;
919 keyRelation = compare( *element, *curEl );
922 if ( keyRelation < 0 )
923 curEl = curEl->BASE_EL(left);
924 /* Do we go right? */
925 else if ( keyRelation > 0 )
926 curEl = curEl->BASE_EL(right);
927 /* We have hit the target. */
938 * \brief Insert a new element into the tree with given key.
940 * If the key is not already in the tree then a new element is made using the
941 * Element(const Key &key) constructor and the insert succeeds. If lastFound is
942 * given then it is set to the element inserted. If the insert fails then
943 * lastFound is set to the existing element in the tree that has the same key as
946 * \returns The new element upon success, null upon failure.
948 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::
949 insert( const Key &key, Element **lastFound )
952 Element *curEl = root, *parentEl = 0;
953 Element *lastLess = 0;
957 /* We are at an external element and did not find the key we were
958 * looking for. Create the new element, attach it underneath the leaf
960 Element *element = new Element( key );
961 attachRebal( element, parentEl, lastLess );
963 if ( lastFound != 0 )
964 *lastFound = element;
968 keyRelation = compare( key, curEl->BASEKEY(getKey()) );
971 if ( keyRelation < 0 ) {
972 parentEl = lastLess = curEl;
973 curEl = curEl->BASE_EL(left);
975 /* Do we go right? */
976 else if ( keyRelation > 0 ) {
978 curEl = curEl->BASE_EL(right);
980 /* We have hit the target. */
982 if ( lastFound != 0 )
991 * \brief Insert a new element into the tree with key and value.
993 * If the key is not already in the tree then a new element is constructed and
994 * the insert succeeds. If lastFound is given then it is set to the element
995 * inserted. If the insert fails then lastFound is set to the existing element in
996 * the tree that has the same key as element. This insert routine is only
997 * available in AvlMap because it is the only class that knows about a Value
1000 * \returns The new element upon success, null upon failure.
1002 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::
1003 insert( const Key &key, const Value &val, Element **lastFound )
1006 Element *curEl = root, *parentEl = 0;
1007 Element *lastLess = 0;
1011 /* We are at an external element and did not find the key we were
1012 * looking for. Create the new element, attach it underneath the leaf
1014 Element *element = new Element( key, val );
1015 attachRebal( element, parentEl, lastLess );
1017 if ( lastFound != 0 )
1018 *lastFound = element;
1022 keyRelation = compare(key, curEl->getKey());
1024 /* Do we go left? */
1025 if ( keyRelation < 0 ) {
1026 parentEl = lastLess = curEl;
1027 curEl = curEl->BASE_EL(left);
1029 /* Do we go right? */
1030 else if ( keyRelation > 0 ) {
1032 curEl = curEl->BASE_EL(right);
1034 /* We have hit the target. */
1036 if ( lastFound != 0 )
1042 #endif /* AVLTREE_MAP */
1046 * \brief Find a element in the tree with the given key.
1048 * \returns The element if key exists, null if the key does not exist.
1050 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::
1051 find( const Key &key ) const
1053 Element *curEl = root;
1057 keyRelation = compare( key, curEl->BASEKEY(getKey()) );
1059 /* Do we go left? */
1060 if ( keyRelation < 0 )
1061 curEl = curEl->BASE_EL(left);
1062 /* Do we go right? */
1063 else if ( keyRelation > 0 )
1064 curEl = curEl->BASE_EL(right);
1065 /* We have hit the target. */
1075 * \brief Find a element, then detach it from the tree.
1077 * The element is not deleted.
1079 * \returns The element detached if the key is found, othewise returns null.
1081 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::
1082 detach(const Key &key)
1084 Element *element = find( key );
1093 * \brief Find, detach and delete a element from the tree.
1095 * \returns True if the element was found and deleted, false otherwise.
1097 template <AVLMEL_TEMPDEF> bool AvlTree<AVLMEL_TEMPUSE>::
1098 remove(const Key &key)
1100 /* Assume not found. */
1101 bool retVal = false;
1103 /* Look for the key. */
1104 Element *element = find( key );
1105 if ( element != 0 ) {
1106 /* If found, detach the element and delete. */
1115 #endif /* AVL_BASIC */
1116 #endif /* AVL_KEYLESS */
1120 * \brief Detach and delete a element from the tree.
1122 * If the element is not in the tree then undefined behaviour results.
1124 template <AVLMEL_TEMPDEF> void AvlTree<AVLMEL_TEMPUSE>::
1125 remove(Element *element)
1127 /* Detach and delete. */
1133 * \brief Detach a element from the tree.
1135 * If the element is not in the tree then undefined behaviour results.
1137 * \returns The element given.
1139 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::
1140 detach(Element *element)
1142 Element *replacement, *fixfrom;
1143 long lheight, rheight;
1146 /* Remove the element from the ordered list. */
1147 BASELIST::detach( element );
1150 /* Update treeSize. */
1153 /* Find a replacement element. */
1154 if (element->BASE_EL(right))
1156 /* Find the leftmost element of the right subtree. */
1157 replacement = element->BASE_EL(right);
1158 while (replacement->BASE_EL(left))
1159 replacement = replacement->BASE_EL(left);
1161 /* If replacing the element the with its child then we need to start
1162 * fixing at the replacement, otherwise we start fixing at the
1163 * parent of the replacement. */
1164 if (replacement->BASE_EL(parent) == element)
1165 fixfrom = replacement;
1167 fixfrom = replacement->BASE_EL(parent);
1170 if ( element == head )
1174 removeEl(replacement, replacement->BASE_EL(right));
1175 replaceEl(element, replacement);
1177 else if (element->BASE_EL(left))
1179 /* Find the rightmost element of the left subtree. */
1180 replacement = element->BASE_EL(left);
1181 while (replacement->BASE_EL(right))
1182 replacement = replacement->BASE_EL(right);
1184 /* If replacing the element the with its child then we need to start
1185 * fixing at the replacement, otherwise we start fixing at the
1186 * parent of the replacement. */
1187 if (replacement->BASE_EL(parent) == element)
1188 fixfrom = replacement;
1190 fixfrom = replacement->BASE_EL(parent);
1193 if ( element == tail )
1197 removeEl(replacement, replacement->BASE_EL(left));
1198 replaceEl(element, replacement);
1202 /* We need to start fixing at the parent of the element. */
1203 fixfrom = element->BASE_EL(parent);
1206 if ( element == head )
1207 head = element->BASE_EL(parent);
1208 if ( element == tail )
1209 tail = element->BASE_EL(parent);
1212 /* The element we are deleting is a leaf element. */
1213 removeEl(element, 0);
1216 /* If fixfrom is null it means we just deleted
1217 * the root of the tree. */
1221 /* Fix the heights after the deletion. */
1222 recalcHeights(fixfrom);
1224 /* Fix every unbalanced element going up in the tree. */
1225 Element *ub = findFirstUnbalEl(fixfrom);
1228 /* Find the element to rebalance by moving down from the first unbalanced
1229 * element 2 levels in the direction of the greatest heights. On the
1230 * second move down, the heights may be equal ( but not on the first ).
1231 * In which case go in the direction of the first move. */
1232 lheight = ub->BASE_EL(left) ? ub->BASE_EL(left)->BASE_EL(height) : 0;
1233 rheight = ub->BASE_EL(right) ? ub->BASE_EL(right)->BASE_EL(height) : 0;
1234 assert( lheight != rheight );
1235 if (rheight > lheight)
1237 ub = ub->BASE_EL(right);
1238 lheight = ub->BASE_EL(left) ?
1239 ub->BASE_EL(left)->BASE_EL(height) : 0;
1240 rheight = ub->BASE_EL(right) ?
1241 ub->BASE_EL(right)->BASE_EL(height) : 0;
1242 if (rheight > lheight)
1243 ub = ub->BASE_EL(right);
1244 else if (rheight < lheight)
1245 ub = ub->BASE_EL(left);
1247 ub = ub->BASE_EL(right);
1251 ub = ub->BASE_EL(left);
1252 lheight = ub->BASE_EL(left) ?
1253 ub->BASE_EL(left)->BASE_EL(height) : 0;
1254 rheight = ub->BASE_EL(right) ?
1255 ub->BASE_EL(right)->BASE_EL(height) : 0;
1256 if (rheight > lheight)
1257 ub = ub->BASE_EL(right);
1258 else if (rheight < lheight)
1259 ub = ub->BASE_EL(left);
1261 ub = ub->BASE_EL(left);
1265 /* rebalance returns the grandparant of the subtree formed
1266 * by the element that were rebalanced.
1267 * We must continue upward from there rebalancing. */
1268 fixfrom = rebalance(ub);
1270 /* Find the next unbalaced element. */
1271 ub = findFirstUnbalEl(fixfrom);
1279 * \brief Empty the tree and delete all the element.
1281 * Resets the tree to its initial state.
1283 template <AVLMEL_TEMPDEF> void AvlTree<AVLMEL_TEMPUSE>::empty()
1286 /* Recursively delete from the tree structure. */
1287 deleteChildrenOf(root);
1293 BASELIST::abandon();
1299 * \brief Forget all element in the tree.
1301 * Does not delete element. Resets the the tree to it's initial state.
1303 template <AVLMEL_TEMPDEF> void AvlTree<AVLMEL_TEMPUSE>::abandon()
1309 BASELIST::abandon();
1313 /* Recursively delete all the children of a element. */
1314 template <AVLMEL_TEMPDEF> void AvlTree<AVLMEL_TEMPUSE>::
1315 deleteChildrenOf( Element *element )
1318 if (element->BASE_EL(left)) {
1319 deleteChildrenOf(element->BASE_EL(left));
1321 /* Delete left element. */
1322 delete element->BASE_EL(left);
1323 element->BASE_EL(left) = 0;
1326 /* Recurse right. */
1327 if (element->BASE_EL(right)) {
1328 deleteChildrenOf(element->BASE_EL(right));
1330 /* Delete right element. */
1331 delete element->BASE_EL(right);
1332 element->BASE_EL(left) = 0;
1336 /* rebalance from a element whose gradparent is unbalanced. Only
1337 * call on a element that has a grandparent. */
1338 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::
1339 rebalance(Element *n)
1341 long lheight, rheight;
1343 Element *t1, *t2, *t3, *t4;
1345 Element *p = n->BASE_EL(parent); /* parent (Non-NUL). L*/
1346 Element *gp = p->BASE_EL(parent); /* Grand-parent (Non-NULL). */
1347 Element *ggp = gp->BASE_EL(parent); /* Great grand-parent (may be NULL). */
1349 if (gp->BASE_EL(right) == p)
1355 if (p->BASE_EL(right) == n)
1366 t1 = gp->BASE_EL(left);
1367 t2 = p->BASE_EL(left);
1368 t3 = n->BASE_EL(left);
1369 t4 = n->BASE_EL(right);
1382 t1 = gp->BASE_EL(left);
1383 t2 = n->BASE_EL(left);
1384 t3 = n->BASE_EL(right);
1385 t4 = p->BASE_EL(right);
1394 if (p->BASE_EL(right) == n)
1405 t1 = p->BASE_EL(left);
1406 t2 = n->BASE_EL(left);
1407 t3 = n->BASE_EL(right);
1408 t4 = gp->BASE_EL(right);
1421 t1 = n->BASE_EL(left);
1422 t2 = n->BASE_EL(right);
1423 t3 = p->BASE_EL(right);
1424 t4 = gp->BASE_EL(right);
1428 /* Perform rotation.
1431 /* Tie b to the great grandparent. */
1434 else if ( ggp->BASE_EL(left) == gp )
1435 ggp->BASE_EL(left) = b;
1437 ggp->BASE_EL(right) = b;
1438 b->BASE_EL(parent) = ggp;
1440 /* Tie a as a leftchild of b. */
1441 b->BASE_EL(left) = a;
1442 a->BASE_EL(parent) = b;
1444 /* Tie c as a rightchild of b. */
1445 b->BASE_EL(right) = c;
1446 c->BASE_EL(parent) = b;
1448 /* Tie t1 as a leftchild of a. */
1449 a->BASE_EL(left) = t1;
1450 if ( t1 != 0 ) t1->BASE_EL(parent) = a;
1452 /* Tie t2 as a rightchild of a. */
1453 a->BASE_EL(right) = t2;
1454 if ( t2 != 0 ) t2->BASE_EL(parent) = a;
1456 /* Tie t3 as a leftchild of c. */
1457 c->BASE_EL(left) = t3;
1458 if ( t3 != 0 ) t3->BASE_EL(parent) = c;
1460 /* Tie t4 as a rightchild of c. */
1461 c->BASE_EL(right) = t4;
1462 if ( t4 != 0 ) t4->BASE_EL(parent) = c;
1464 /* The heights are all recalculated manualy and the great
1465 * grand-parent is passed to recalcHeights() to ensure
1466 * the heights are correct up the tree.
1468 * Note that recalcHeights() cuts out when it comes across
1469 * a height that hasn't changed.
1472 /* Fix height of a. */
1473 lheight = a->BASE_EL(left) ? a->BASE_EL(left)->BASE_EL(height) : 0;
1474 rheight = a->BASE_EL(right) ? a->BASE_EL(right)->BASE_EL(height) : 0;
1475 a->BASE_EL(height) = (lheight > rheight ? lheight : rheight) + 1;
1477 /* Fix height of c. */
1478 lheight = c->BASE_EL(left) ? c->BASE_EL(left)->BASE_EL(height) : 0;
1479 rheight = c->BASE_EL(right) ? c->BASE_EL(right)->BASE_EL(height) : 0;
1480 c->BASE_EL(height) = (lheight > rheight ? lheight : rheight) + 1;
1482 /* Fix height of b. */
1483 lheight = a->BASE_EL(height);
1484 rheight = c->BASE_EL(height);
1485 b->BASE_EL(height) = (lheight > rheight ? lheight : rheight) + 1;
1487 /* Fix height of b's parents. */
1492 /* Recalculates the heights of all the ancestors of element. */
1493 template <AVLMEL_TEMPDEF> void AvlTree<AVLMEL_TEMPUSE>::
1494 recalcHeights(Element *element)
1496 long lheight, rheight, new_height;
1497 while ( element != 0 )
1499 lheight = element->BASE_EL(left) ? element->BASE_EL(left)->BASE_EL(height) : 0;
1500 rheight = element->BASE_EL(right) ? element->BASE_EL(right)->BASE_EL(height) : 0;
1502 new_height = (lheight > rheight ? lheight : rheight) + 1;
1504 /* If there is no chage in the height, then there will be no
1505 * change in any of the ancestor's height. We can stop going up.
1506 * If there was a change, continue upward. */
1507 if (new_height == element->BASE_EL(height))
1510 element->BASE_EL(height) = new_height;
1512 element = element->BASE_EL(parent);
1516 /* Finds the first element whose grandparent is unbalanced. */
1517 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::
1518 findFirstUnbalGP(Element *element)
1520 long lheight, rheight, balanceProp;
1523 if ( element == 0 || element->BASE_EL(parent) == 0 ||
1524 element->BASE_EL(parent)->BASE_EL(parent) == 0 )
1527 /* Don't do anything if we we have no grandparent. */
1528 gp = element->BASE_EL(parent)->BASE_EL(parent);
1531 lheight = gp->BASE_EL(left) ? gp->BASE_EL(left)->BASE_EL(height) : 0;
1532 rheight = gp->BASE_EL(right) ? gp->BASE_EL(right)->BASE_EL(height) : 0;
1533 balanceProp = lheight - rheight;
1535 if ( balanceProp < -1 || balanceProp > 1 )
1538 element = element->BASE_EL(parent);
1539 gp = gp->BASE_EL(parent);
1545 /* Finds the first element that is unbalanced. */
1546 template <AVLMEL_TEMPDEF> Element *AvlTree<AVLMEL_TEMPUSE>::
1547 findFirstUnbalEl(Element *element)
1552 while ( element != 0 )
1554 long lheight = element->BASE_EL(left) ?
1555 element->BASE_EL(left)->BASE_EL(height) : 0;
1556 long rheight = element->BASE_EL(right) ?
1557 element->BASE_EL(right)->BASE_EL(height) : 0;
1558 long balanceProp = lheight - rheight;
1560 if ( balanceProp < -1 || balanceProp > 1 )
1563 element = element->BASE_EL(parent);
1568 /* Replace a element in the tree with another element not in the tree. */
1569 template <AVLMEL_TEMPDEF> void AvlTree<AVLMEL_TEMPUSE>::
1570 replaceEl(Element *element, Element *replacement)
1572 Element *parent = element->BASE_EL(parent),
1573 *left = element->BASE_EL(left),
1574 *right = element->BASE_EL(right);
1576 replacement->BASE_EL(left) = left;
1578 left->BASE_EL(parent) = replacement;
1579 replacement->BASE_EL(right) = right;
1581 right->BASE_EL(parent) = replacement;
1583 replacement->BASE_EL(parent) = parent;
1586 if (parent->BASE_EL(left) == element)
1587 parent->BASE_EL(left) = replacement;
1589 parent->BASE_EL(right) = replacement;
1594 replacement->BASE_EL(height) = element->BASE_EL(height);
1597 /* Removes a element from a tree and puts filler in it's place.
1598 * Filler should be null or a child of element. */
1599 template <AVLMEL_TEMPDEF> void AvlTree<AVLMEL_TEMPUSE>::
1600 removeEl(Element *element, Element *filler)
1602 Element *parent = element->BASE_EL(parent);
1606 if (parent->BASE_EL(left) == element)
1607 parent->BASE_EL(left) = filler;
1609 parent->BASE_EL(right) = filler;
1615 filler->BASE_EL(parent) = parent;
1620 #ifdef AAPL_NAMESPACE