Code Fragment: AVLTree1



template <typename Key, typename Element>
class AVLTree : public BinarySearchTree<Key, Element, AVLItem<Key, Element> > {
protected: 						// local types
  typedef AVLItem<Key, Element>		Item;		// a tree node item
  typedef BinarySearchTree<Key, Element, Item>  BST;	// base search tree
  typedef BST::BTPosition 		BTPosition;	// a tree position
public: 						// public types
  typedef BST::Position 		Position;	// position
  // ... (insert AVLItem here)
protected: 						// local utilities
  int height(const BTPosition& p) const {		// get height of p
    if(T.isExternal(p)) return 0;
    else return p.element().height();
  }
  void setHeight(BTPosition p) {			// set height of p
    int leftHeight   = height(T.leftChild(p));
    int rightHeight  = height(T.rightChild(p));
    int maxHeight    = max(leftHeight, rightHeight);
    p.element().setHeight(1 + maxHeight);
  }
  bool isBalanced(const BTPosition& p) const {		// is p balanced?
    int bf = height(T.leftChild(p)) - height(T.rightChild(p));
    return ((-1 <= bf) && (bf <= 1));
  }
  BTPosition tallGrandchild(const BTPosition& p) const;	// get tallest grandchild
  // ... (insert rebalance() here)
public:
  AVLTree() : BST() { }					// constructor
  void insertItem(const Key& k, const Element& e) {	// insert (key,element)
    BTPosition p = inserter(k, e);			// insert in base tree
    setHeight(p);					// compute its height
    rebalance(p);					// rebalance if needed
  }
  void removeElement(const Key& k)			// remove using key
      throw(NonexistentElementException) {
    BTPosition p = finder(k, T.root());			// find in base tree
    if (p.isNull())					// not found?
      throw NonexistentElementException("Remove nonexistent element");
    BTPosition r = remover(p);				// remove it
    rebalance(r);					// rebalance if needed
  }
};