/** * ***************************************************************************** * AVLTree.h: a simple implementation of the AVL Tree * Author: Hung Q. Ngo * ***************************************************************************** */ #ifndef AVLTREE_H_ #define AVLTREE_H_ #include #include template class AVLTree { public: AVLTree() : root(NULL) { } void inorder_print() { inorder_print(root); std::cout << std::endl; } void preorder_print() { preorder_print(root); std::cout << std::endl; } void postorder_print() { postorder_print(root); std::cout << std::endl; } bool insert(Key, Value); bool remove(Key); bool find(Key key) { return search(root, key) != NULL; } const Value& get(Key); const Value& minimum(); const Value& maximum(); void clear() { clear(root); } private: // The node is similar to a BSTNode; use parent pointer to simplify codes // A tree is simply a pointer to a BSTNode, we will assume that variables of // type Key are comparable using <, <=, ==, >=, and > // we do not allow default keys and values struct AVLNode { enum { LEFT_HEAVY = 1, BALANCED = 0, RIGHT_HEAVY = -1}; int balance; Key key; Value value; AVLNode* left; AVLNode* right; AVLNode* parent; AVLNode(const Key& k, const Value& v) : key(k), value(v), parent(NULL), left(NULL), right(NULL), balance(BALANCED) {} std::string to_string() const { std::ostringstream oss; oss << key << "(" << balance << ")"; return oss.str(); } }; AVLNode* root; AVLNode* successor(AVLNode* node); AVLNode* predecessor(AVLNode* node); AVLNode* search(AVLNode*, Key); void rebalance(AVLNode*); void right_rotate(AVLNode*&); void left_rotate(AVLNode*&); void inorder_print(AVLNode*); void preorder_print(AVLNode*); void postorder_print(AVLNode*); void clear(AVLNode*&); }; #include "AVLTree.cpp" // only done for template classes #endif