參考連結:http://blog.csdn.net/cjbct/article/details/53613436
AVL樹中,最重要的便是讓樹重新平衡,我們稱個過程為旋轉。旋轉包括四種,主要是由於插入位置的原因導致的。旋轉的過程可以看代碼中的注釋部分(569行-639行),有詳細的解釋。
這次編寫的過程中,將C++模板類的定義了和函數實現進行了分開(但是仍然在標頭檔中),遇到了比較多的問題。先看看代碼,然後對裡面我遇到的問題進行總結。
先看看AVL樹的實現代碼 AVLTree.h:
[cpp] view plain copy #ifndef AVL_TREE_H #define AVL_TREE_H #include<iostream> using namespace std; template <typename Comparable> class AVLTree { public: typedef enum _order {PREORDER, INORDER, POSTORDER} ORDER; // 通過enum定義常量 public: AVLTree() :m_root(nullptr){} AVLTree(const AVLTree &rhs) { m_root = clone(rhs.m_root); } ~AVLTree() { makeEmpty(); } /** * 返回樹的高度。空樹的高度定義為-1 */ int getHeight() const { return m_root.height; } /** * 找到樹中的最小值,通過調用private的findMin實現遞迴 */ const Comparable & findMin() const { return findMin(m_root)->element; } /** * 找到樹中的最大值,通過調用private的findMax實現遞迴 */ const Comparable & findMax() const { return findMax(m_root)->element; } /** * 當x找到時返回真,否則返回假 * 調用了private的那個同名函數,這個是為了遞迴實現 *(因為private中包含了一個AVLNode的指標t) */ bool contains(const Comparable &x) const {