AVL树(C++模块实现)

AVL树又叫自平衡二叉查找树,在效率上不比红黑树,但是是红黑树的基础!下面是构造一棵AVL树的完整代码!

  1. //AVLTree.h
  2. //参考:http://www.cppblog.com/goodwin/archive/2011/08/08/152797.html
  3. #ifndef _AVLTREE_H_
  4. #define _AVLTREE_H_
  5. #include “Stack.h”
  6. #include “Queue.h”
  7. #define SAFE_CALL(p) p == NULL ? NULL : p
  8. template <typename T>
  9. T Max(T a,T b)
  10. {
  11.     return (a)>(b) ? (a) : (b);
  12. }
  13. namespace _AVL_Tree_
  14. {
  15.     #define Balance(a)    abs((SAFE_CALL(a>mpLeft)>mHeigh) (SAFE_CALL(a>mpRight)>mHeigh))
  16.     #define isLeftHigh(a)    ((SAFE_CALL(a>mpLeft)>mHeigh) > (SAFE_CALL(a>mpRight)>mHeigh)) ? true : false
  17.     #define isLeftTree(a,b) ((a)>mpLeft == (b)) ? true : false
  18. #define isRightTree(a,b) ((a)>mpRight == (b)) ? true : false
  19.     typedef enum _position_
  20.     {
  21.         enPosi_Root = 0,
  22.         enPosi_Left,
  23.         enPosi_Right,
  24.         enPosi_Equal,
  25.         enPosiMax
  26.     }POSITION;
  27.     typedef enum _rotal_type_
  28.     {
  29.         enRotalType_Anonymous,
  30.         enRotalType_LeftLeft = 1,
  31. enRotalType_RightRight,
  32.         enRotalType_LeftRight,
  33.         enRotalType_RightLeft,
  34.         enRotalType_MaxType
  35.     }RotalType;
  36.     template <typename T>
  37.     class TreeNode
  38.     {
  39.     public:
  40.         TreeNode()
  41.         {
  42.             mHeigh    = 0;
  43.             mElement = T();
  44.             mpLeft = mpRight = mpParent = NULL;
  45.         }
  46.         ~TreeNode()
  47.         {
  48.             mElement = T();
  49.             mpLeft = mpRight = mpParent = NULL;
  50.         }
  51.         T                mElement;
  52.         int            mHeigh;
  53.         TreeNode<T>*    mpLeft;
  54.         TreeNode<T>*    mpRight;
  55.         TreeNode<T>*    mpParent;
  56.     };
  57.     template <typename T>
  58.     class AVLTree
  59.     {
  60.     public:
  61.         AVLTree();
  62.         ~AVLTree();
  63.         bool    insert(const T& element);
  64.         bool    remove(const T& element);
  65.         bool clear();
  66.         //POSITION:返回找到的插入点的位置,s:返回在遍历过程中从树根到找到的插入点的路径(主要是用来旋转用)。
  67.         POSITION find(const T& element,Stack<TreeNode<T>*>& s);
  68.         //中序遍历
  69.         bool inorderTravel(void);
  70.         //先序遍历
  71.         bool prevorederTravel(void);
  72.         //中序遍历,并把遍历的结果放到栈中,用户销毁这棵树。
  73.         bool inorderTravel(Stack<TreeNode<T>*>& s);
  74.         //求一棵树的最大长度的路径。
  75.         bool getLongestPath(const TreeNode<T>* pRoot,Queue<TreeNode<T>*>& q);
  76.         //检查是否是AVL树。
  77.         bool checkIsAVLTree(void);
  78.         //把AVL树的信息丰收放到文件中
  79.         void saveAVLTreeToFile(const char* pFileName);
  80.     protected:
  81.         TreeNode<T>* CreateNode(const T& element);
  82.         TreeNode<T>* RightRightRotal(TreeNode<T>* pNode);
  83.         TreeNode<T>* LeftLeftRotal(TreeNode<T>* pNode);
  84.         TreeNode<T>* LeftRightRotal(TreeNode<T>* pNode);
  85.         TreeNode<T>* RightLeftRotal(TreeNode<T>* pNode);
  86.         RotalType checkRotalType(TreeNode<T>* pPParentNode,TreeNode<T>* pParentNode,TreeNode<T>* pNode);
  87.         TreeNode<T>* rotalTree(TreeNode<T>* pPParentNode,TreeNode<T>* pParentNode,TreeNode<T>* pNode);
  88.         //当要进行旋转时,判定需求旋转的类型。
  89.         RotalType checkRotalType(TreeNode<T>* pRootNode);
  90.         //对以pRootNode为根的进行旋转
  91.         TreeNode<T>* rotalTree(TreeNode<T>* pRootNode);
  92.         //对树进行平衡处理
  93.         bool balanceTree(TreeNode<T>* pRootNode);
  94.         //获取节点pNode的中序遍历【前驱】节点
  95.         TreeNode<T>* getPrevNode(TreeNode<T>* pNode);
  96.         //获取节点pNode的中序遍历【后继】节点
  97.         TreeNode<T>* getNextNode(TreeNode<T>* pNode);
  98.     private:
  99.         TreeNode<T>* mpRoot;
  100.     };
  101.     template <typename T>
  102.     AVLTree<T>::AVLTree()
  103.     {
  104.         mpRoot = new TreeNode<T>;
  105.         if (!mpRoot) throw(“malloc memery failed.”);
  106.         mpRoot>mElement = 1;
  107.         mpRoot>mHeigh = 0;
  108.         mpRoot>mpLeft = mpRoot>mpParent = mpRoot>mpRight = NULL;
  109.     }
  110.     template <typename T>
  111.     AVLTree<T>::~AVLTree()
  112.     {
  113.         this>clear();
  114.         delete this>mpRoot;
  115.         this>mpRoot = NULL;
  116.     }
  117.     template <typename T>
  118.     TreeNode<T>* AVLTree<T>::CreateNode(const T& element)
  119.     {
  120.         TreeNode<T>* pNode = new TreeNode<T>;
  121.         if (pNode)
  122.         {
  123.             pNode>mElement    = element;
  124.             pNode>mpLeft    = pNode>mpRight = pNode>mpParent    = NULL;
  125.             pNode>mHeigh    = 1;
  126.             return pNode;
  127.         }
  128.         return NULL;
  129.     }
  130.     template <typename T>
  131.     TreeNode<T>* AVLTree<T>::RightRightRotal(TreeNode<T>* pNode)
  132.     {
  133.         TreeNode<T>* pRightChild = pNode>mpRight;
  134.         //cout << “RightRightRotal mElement:” << pNode>mElement << endl;
  135.         pNode>mHeigh    = Max((SAFE_CALL(pNode>mpLeft)>mHeigh),(SAFE_CALL(pRightChild>mpLeft)>mHeigh)) + 1;
  136.         pRightChild>mHeigh = Max((SAFE_CALL(pRightChild>mpRight)>mHeigh),(pNode>mHeigh)) + 1;
  137.         pNode>mpRight = pRightChild>mpLeft;
  138.         if (pRightChild>mpLeft && pRightChild>mpLeft>mpParent)
  139.         {
  140.             pRightChild>mpLeft>mpParent = pNode;
  141.         }
  142.         pRightChild>mpLeft = pNode;
  143.         pNode>mpParent = pRightChild;
  144.         return pRightChild;
  145.     }
  146.     template <typename T>
  147.     TreeNode<T>* AVLTree<T>::LeftLeftRotal(TreeNode<T>* pNode)
  148.     {
  149.         TreeNode<T>* pLeftChild = pNode>mpLeft;
  150.         //cout << “LeftLeftRotal mElement:” << pNode>mElement << endl;
  151.         pNode>mHeigh    = Max((SAFE_CALL(pLeftChild>mpRight)>mHeigh),(SAFE_CALL(pNode>mpRight)>mHeigh)) + 1;
  152.         pLeftChild>mHeigh = Max((SAFE_CALL(pLeftChild>mpLeft)>mHeigh),pNode>mHeigh) + 1;
  153.         pNode>mpLeft = pLeftChild>mpRight;
  154.         if (pLeftChild>mpRight && pLeftChild>mpRight>mpParent)
  155.         {
  156.             pLeftChild>mpRight>mpParent = pNode;
  157.         }
  158.         pLeftChild>mpRight = pNode;
  159.         pNode>mpParent = pLeftChild;
  160.         return pLeftChild;
  161.     }
  162.     template <typename T>
  163.     TreeNode<T>* AVLTree<T>::LeftRightRotal(TreeNode<T>* pNode)
  164.     {
  165.         TreeNode<T>* pLeftChild = pNode>mpLeft;
  166.         TreeNode<T>* pTmp        = pLeftChild;
  167.         //左旋转
  168.         pLeftChild = this>RightRightRotal(pLeftChild);
  169.         pNode>mpLeft = pLeftChild;
  170.         pLeftChild>mpParent = pNode;
  171.         pTmp>mpParent = pLeftChild;
  172.         //右旋转
  173.         pNode =this>LeftLeftRotal(pNode);
  174.         return pNode;
  175.     }
  176.     template <typename T>
  177.     TreeNode<T>* AVLTree<T>::RightLeftRotal(TreeNode<T>* pNode)
  178.     {
  179.         TreeNode<T>* pRightChild = pNode>mpRight;
  180.         TreeNode<T>* pTmp        = pRightChild;
  181.         //右旋转
  182.         pRightChild = this>LeftLeftRotal(pRightChild);
  183.         pNode >mpRight = pRightChild;
  184.        
  185.         pRightChild>mpParent = pNode;
  186.         pTmp>mpParent = pRightChild;
  187.         //左旋转
  188.         pNode = this>RightRightRotal(pNode);
  189.         return pNode;
  190.     }
  191.     template <typename T>
  192.     RotalType AVLTree<T>::checkRotalType(TreeNode<T>* pPParentNode,TreeNode<T>* pParentNode,TreeNode<T>* pNode)
  193.     {
  194.         bool bPLeft = false,bLeft = false;
  195.         if (pPParentNode>mpLeft == pParentNode)
  196.             bPLeft = true;
  197.         else
  198.             bPLeft = false;
  199.         if (pParentNode>mpLeft == pNode)
  200.             bLeft = true;
  201.         else
  202.             bLeft = false;
  203.         RotalType type ;
  204.         if (bPLeft && bLeft)
  205.             type = enRotalType_LeftLeft;
  206.         else if (!bPLeft && bLeft)
  207.             type = enRotalType_RightLeft;
  208.         else if(bPLeft && !bLeft)
  209.             type = enRotalType_LeftRight;
  210.         else if (!bPLeft && !bLeft )
  211.             type = enRotalType_RightRight;
  212.         return type;
  213.     }
  214.     template <typename T>
  215.     TreeNode<T>* AVLTree<T>::rotalTree(TreeNode<T>* pPParentNode,TreeNode<T>* pParentNode,TreeNode<T>* pNode)
  216.     {
  217.         RotalType type = this>checkRotalType(pPParentNode,pParentNode,pNode);
  218.         switch (type)
  219.         {
  220.         case enRotalType_LeftLeft:
  221.             {
  222.                 return this>LeftLeftRotal(pPParentNode);
  223.             }
  224.         case enRotalType_RightRight:
  225.             {
  226.                 return this>RightRightRotal(pPParentNode);
  227.                 break;
  228.             }
  229.         case enRotalType_LeftRight:
  230.             {
  231.                 return this>LeftRightRotal(pPParentNode);
  232.                 break;
  233.             }
  234.         case enRotalType_RightLeft:
  235.             {
  236.                 return this>RightLeftRotal(pPParentNode);
  237.                 break;
  238.             }
  239.         }
  240.         return NULL;
  241.     }
  242.     //当要进行旋转时,判定需求旋转的类型。
  243.     template <typename T>
  244.     RotalType AVLTree<T>::checkRotalType(TreeNode<T>* pRootNode)
  245.     {
  246.         RotalType type = enRotalType_Anonymous;
  247.         if (Balance(pRootNode) >= 2)
  248.         {
  249.             bool bCLeft = false,bCCLeft = false;
  250.             Queue<TreeNode<T>*> q;
  251.             this>getLongestPath(pRootNode,q);
  252.             TreeNode<T>* pChildNode = q.front();    //先把树根出列
  253.             pChildNode= q.front();
  254.             bCLeft = (pRootNode>mpLeft == pChildNode);
  255.             TreeNode<T>* pCChildNode = q.front();
  256.             bCCLeft = (pChildNode>mpLeft == pCChildNode);
  257.             q.clear();
  258.             if (bCLeft && bCCLeft)
  259.                 type = enRotalType_LeftLeft;
  260.             else if (!bCLeft && bCCLeft)
  261.                 type = enRotalType_RightLeft;
  262.             else if(bCLeft && !bCCLeft)
  263.                 type = enRotalType_LeftRight;
  264.             else if (!bCLeft && !bCCLeft )
  265.                 type = enRotalType_RightRight;
  266.         }
  267.         return type;
  268.     }
  269.    
  270.     //对以pRootNode为根的进行旋转
  271.     template <typename T>
  272.     TreeNode<T>* AVLTree<T>::rotalTree(TreeNode<T>* pRootNode)
  273.     {
  274.         RotalType type = this>checkRotalType(pRootNode);
  275.         switch (type)
  276.         {
  277.         case enRotalType_Anonymous:
  278.             {
  279.                 return NULL;
  280.             }
  281.         case enRotalType_LeftLeft:
  282.             {
  283.                 return this>LeftLeftRotal(pRootNode);
  284.             }
  285.         case enRotalType_RightRight:
  286.             {
  287.                 return this>RightRightRotal(pRootNode);
  288.             }
  289.         case enRotalType_LeftRight:
  290.             {
  291.                 return this>LeftRightRotal(pRootNode);
  292.             }
  293.         case enRotalType_RightLeft:
  294.             {
  295.                 return this>RightLeftRotal(pRootNode);
  296.             }
  297.         }
  298.         return NULL;       
  299.     }
  300.     //对树进行平衡处理
  301.     template <typename T>
  302.     bool AVLTree<T>::balanceTree(TreeNode<T>* pRootNode)
  303.     {
  304.         while (pRootNode && pRootNode != this>mpRoot)
  305.         {
  306.             pRootNode>mHeigh = Max((SAFE_CALL(pRootNode>mpLeft)>mHeigh) , (SAFE_CALL(pRootNode>mpRight)>mHeigh)) + 1;
  307.             if (Balance(pRootNode) >= 2)
  308.             {
  309.                 bool bLeft = false;
  310.                 TreeNode<T>* pPPNode = pRootNode>mpParent;
  311.                 bLeft = (pPPNode>mpLeft == pRootNode);
  312.                 pRootNode = this>rotalTree(pRootNode);
  313.                 if (bLeft)
  314.                     pPPNode>mpLeft = pRootNode;
  315.                 else
  316.                     pPPNode>mpRight = pRootNode;
  317.                 pRootNode>mpParent = pPPNode;
  318.             }
  319.             pRootNode = pRootNode>mpParent;
  320.         }
  321.         return true;
  322.     }
  323.     //获取节点pNode的中序遍历【前驱】节点
  324.     template <typename T>
  325.     TreeNode<T>* AVLTree<T>::getPrevNode(TreeNode<T>* pNode)
  326.     {
  327.         TreeNode<T>* pTmpNode = pNode>mpLeft;
  328.         while (pTmpNode && pTmpNode>mpRight)
  329.             pTmpNode = pTmpNode>mpRight;
  330.         return pTmpNode;           
  331.     }
  332.     //获取节点pNode的中序遍历【后继】节点
  333.     template <typename T>
  334.     TreeNode<T>* AVLTree<T>::getNextNode(TreeNode<T>* pNode)
  335.     {
  336.         TreeNode<T>* pTmpNode = pNode>mpRight;
  337.         while (pTmpNode && pTmpNode>mpLeft)
  338.             pTmpNode = pTmpNode>mpLeft;
  339.         return pTmpNode;
  340.     }
  341.     template <typename T>
  342.     bool    AVLTree<T>::insert(const T& element)
  343.     {
  344.         TreeNode<T>* pNode = NULL;
  345.         TreeNode<T>* pInNode    = NULL;    //插入点节点
  346.         Stack<TreeNode<T>*> s;
  347.         POSITION pos = this>find(element,s);
  348.         switch (pos)
  349.         {
  350.         case enPosi_Equal:
  351.             {
  352.                 static int iCount = 0;
  353.                 cout << “—-enPosi_Equal–iCount:”<<++iCount<<“–element:”<< element << endl;               
  354.                 break;
  355.             }
  356.         case enPosi_Root:
  357.             {
  358.                 pNode = this>CreateNode(element);
  359.                 this>mpRoot>mpLeft    = pNode;
  360.                 pNode>mpParent = this>mpRoot;
  361.                 break;
  362.             }
  363.         case enPosi_Left:
  364.             {
  365.                 pNode = this>CreateNode(element);
  366.                 pInNode = s.pop();
  367.                 pInNode>mpLeft = pNode;
  368.                 pNode>mpParent = pInNode;
  369.                 pInNode>mHeigh = Max((SAFE_CALL(pInNode>mpLeft)>mHeigh) ,(SAFE_CALL(pInNode>mpRight)>mHeigh)) + 1;
  370.                 TreeNode<T>* pParentNode = pInNode>mpParent;
  371.                 if (pParentNode && pParentNode != this>mpRoot)
  372.                 {
  373.                     this>balanceTree(pParentNode);
  374.                 }
  375.                 break;
  376.             }
  377.         case enPosi_Right:
  378.             {
  379.                 pNode = this>CreateNode(element);
  380.                 TreeNode<T>* pInNode = s.pop();
  381.                 pInNode>mpRight = pNode;
  382.                 pNode>mpParent = pInNode;
  383.                 pInNode>mHeigh = Max((SAFE_CALL(pInNode>mpRight)>mHeigh) , (SAFE_CALL(pInNode>mpLeft)>mHeigh)) + 1;
  384.                 TreeNode<T>* pParentNode = pInNode>mpParent;
  385.                 if (pParentNode && pParentNode != this>mpRoot)
  386.                 {
  387.                     this>balanceTree(pParentNode);
  388.                 }
  389.                 break;
  390.             }       
  391.         }
  392.         s.clear();
  393.         return true;
  394.     }
  395.     template <typename T>
  396.     bool AVLTree<T>::remove(const T& element)
  397.     {
  398.         TreeNode<T>* pDelNode    = NULL;    //插入点节点
  399.         Stack<TreeNode<T>*> s;
  400.         POSITION pos = this>find(element,s);
  401.         if (s.isEmpty())    goto OVER;
  402.         switch (pos)
  403.         {
  404.         case enPosi_Equal:
  405.             {
  406.                 pDelNode = s.pop();
  407.                 if (pDelNode>mpLeft == NULL && pDelNode>mpRight == NULL)
  408.                 {//1.删除的节点没有子树
  409.                     TreeNode<T>* pParentNode = pDelNode>mpParent;
  410.                     if (pParentNode && isLeftTree(pParentNode,pDelNode))
  411.                         pParentNode>mpLeft = NULL;
  412.                     else if(pParentNode && isRightTree(pParentNode,pDelNode))
  413.                         pParentNode>mpRight = NULL;
  414.                     this>balanceTree(pParentNode);
  415.                     delete pDelNode;
  416.                     pDelNode = NULL;
  417.                 }
  418.                 else if((pDelNode>mpLeft && pDelNode>mpRight == NULL) ||
  419.                     (pDelNode>mpLeft == NULL && pDelNode>mpRight))
  420.                 {//2.删除的节点有一子树
  421.                     TreeNode<T>* pChildNode = pDelNode>mpLeft;
  422.                     if(!pChildNode)
  423.                         pChildNode = pDelNode>mpRight;
  424.                     TreeNode<T>* pParentNode = pDelNode>mpParent;
  425.                     if (pParentNode && isLeftTree(pParentNode,pDelNode))
  426.                     {//    2.1、删除的结点是其父节点的左子树
  427.                         pParentNode>mpLeft = pChildNode;
  428.                         pChildNode>mpParent = pParentNode;
  429.                         this>balanceTree(pParentNode);
  430.                     }
  431.                     else if(pParentNode && isRightTree(pParentNode,pDelNode))
  432.                     {//2.2、删除的结点是其父节点的右子树
  433.                         pParentNode>mpRight = pChildNode;
  434.                         pChildNode>mpParent = pParentNode;
  435.                         this>balanceTree(pParentNode);
  436.                     }
  437.                     delete pDelNode;
  438.                     pDelNode = NULL;
  439.                 }
  440.                 else if (pDelNode>mpLeft && pDelNode>mpRight)
  441.                 {//3、删除的节点有左右子树
  442.                     /*
  443.                     有两种做法,要删除p的节点:
  444.                     1.把p的左子树设成其父节点的左子树,把p的右子树设成其实左子树的最右边的叶子节点。
  445.                     2.把p的【直接前驱(中序)】替换p,然后把【前驱】的左子树替换成【前驱】的右子树。
  446.                     以下实现是利用第2种方法。
  447.                     */
  448.                     if (pDelNode>mpLeft>mHeigh >= pDelNode>mpRight>mHeigh)
  449.                     {//左子树比右子树高,就用pDelNode的【前驱】替换
  450.                         TreeNode<T>* pPrevNode = this>getPrevNode(pDelNode);
  451.                         pDelNode>mElement = pPrevNode>mElement;
  452.                         TreeNode<T>* pParentNode = pPrevNode>mpParent;
  453.                         pParentNode>mpRight = pPrevNode>mpLeft;
  454.                         if (pPrevNode>mpLeft)
  455.                             pPrevNode>mpLeft>mpParent = pParentNode;
  456.                        
  457.                         this>balanceTree(pParentNode);
  458.                         delete pPrevNode;
  459.                         pPrevNode = NULL;
  460.                     }
  461.                     else
  462.                     {//右子树比左子树高,就用pDelNode的【后继】替换
  463.                         TreeNode<T>* pNextNode = this>getNextNode(pDelNode);
  464.                         pDelNode>mElement = pNextNode>mElement;
  465.                         TreeNode<T>* pParentNode = pNextNode>mpParent;
  466.                         pParentNode>mpLeft = pNextNode>mpRight;
  467.                         if(pNextNode>mpRight)
  468.                             pNextNode>mpRight>mpParent = pParentNode;
  469.                         this>balanceTree(pParentNode);
  470.                         delete pNextNode;
  471.                         pNextNode = NULL;
  472.                     }
  473.                 }
  474.                 break;
  475.             }
  476.         default:
  477.             {
  478.                 goto OVER;
  479.                 break;
  480.             }
  481.         }
  482. OVER:
  483.         s.clear();
  484.         return true;
  485.     }
  486.     template <typename T>
  487.     bool AVLTree<T>::clear()
  488.     {
  489.         Stack<TreeNode<T>*> s;
  490.         this>inorderTravel(s);
  491.         TreeNode<T>* pNode = NULL;
  492.         while ((pNode= s.pop()) != NULL)           
  493.             delete pNode;
  494.         return true;
  495.     }
  496.     //POSITION:返回找到的插入点的位置,s:返回在遍历过程中从树根到找到的插入点的路径(主要是用来旋转用)。
  497.     template <typename T>
  498.     POSITION AVLTree<T>::find(const T& element,Stack<TreeNode<T>* >& s)
  499.     {
  500.         TreeNode<T>* pNode = this>mpRoot>mpLeft;
  501.         POSITION pos = enPosi_Root;
  502.         while (pNode)
  503.         {
  504.             s.push(pNode);
  505.             if (element == pNode>mElement)
  506.             {
  507.                 pos = enPosi_Equal;
  508.                 break;
  509.             }
  510.             else if (element < pNode>mElement)
  511.             {
  512.                 pos = enPosi_Left;
  513.                 if (pNode>mpLeft)
  514.                     pNode = pNode>mpLeft;
  515.                 else
  516.                     break;           
  517.             }
  518.             else if (element > pNode>mElement)
  519.             {               
  520.                 pos = enPosi_Right;
  521.                 if (pNode>mpRight)
  522.                     pNode = pNode>mpRight;   
  523.                 else
  524.                     break;                           
  525.             }           
  526.         }
  527.         return pos;
  528.     }
  529.     //中序遍历
  530.     template <typename T>
  531.     bool AVLTree<T>::inorderTravel(void)
  532.     {
  533.         TreeNode<T>* pNode = this>mpRoot>mpLeft;
  534.         if (pNode)
  535.         {
  536.             Stack<TreeNode<T>*> s;
  537.             while (pNode || !s.isEmpty())
  538.             {
  539.                 while (pNode)
  540.                 {
  541.                     s.push(pNode);
  542.                     pNode = pNode>mpLeft;
  543.                 }
  544.                 pNode = s.pop();
  545.                 if (pNode)
  546.                 {
  547.                     cout << pNode>mElement << ” “;
  548.                     pNode = pNode>mpRight;
  549.                 }               
  550.             }
  551.         }
  552.         return true;
  553.     }
  554.     //先序遍历
  555.     template <typename T>
  556.     bool AVLTree<T>::prevorederTravel(void)
  557.     {
  558.         TreeNode<T>* pNode = this>mpRoot>mpLeft;
  559.         if (pNode)
  560.         {
  561.             Stack<TreeNode<T>*> s;
  562.             while (pNode || !s.isEmpty())
  563.             {           
  564.                 while (pNode)
  565.                 {
  566.                     cout << pNode>mElement << ” “;
  567.                     s.push(pNode);
  568.                     pNode = pNode>mpLeft;
  569.                 }
  570.                 pNode = s.pop();
  571.                 if (pNode)                   
  572.                     pNode = pNode>mpRight;
  573.             }
  574.         }
  575.         return true;
  576.     }
  577.     //中序遍历,并把遍历的结果放到栈中,用户销毁这棵树。
  578.     template <typename T>
  579.     bool AVLTree<T>::inorderTravel(Stack<TreeNode<T>*>& s)
  580.     {
  581.         TreeNode<T>* pNode = this>mpRoot>mpLeft;
  582.         if (pNode)
  583.         {
  584.             Stack<TreeNode<T>*> sTmp;
  585.             while (pNode || !sTmp.isEmpty())
  586.             {
  587.                 while (pNode)
  588.                 {
  589.                     sTmp.push(pNode);
  590.                     pNode = pNode>mpLeft;
  591.                 }
  592.                 pNode = sTmp.pop();
  593.                 if (pNode)
  594.                 {
  595.                     s.push(pNode);
  596.                     pNode = pNode>mpRight;
  597.                 }                       
  598.             }
  599.         }
  600.         return true;
  601.     }
  602.     //求一棵树的最大长度的路径。
  603.     template <typename T>
  604.     bool AVLTree<T>::getLongestPath(const TreeNode<T>* pRoot,Queue<TreeNode<T>*>& q)
  605.     {
  606.         if (!pRoot)    return false;
  607.         q.insert((TreeNode<T>*)(pRoot));
  608.         if ((SAFE_CALL(pRoot>mpLeft)>mHeigh) >= (SAFE_CALL(pRoot>mpRight)>mHeigh))
  609.             return getLongestPath(pRoot>mpLeft,q);
  610.         else
  611.             return getLongestPath(pRoot>mpRight,q);
  612.         return true;
  613.     }
  614.     //检查是否是AVL树。
  615.     template <typename T>
  616.     bool AVLTree<T>::checkIsAVLTree(void)
  617.     {
  618.             Stack<TreeNode<T>*> s;
  619.             this>inorderTravel(s);
  620.             TreeNode<T>* pNode = NULL;
  621.             while ((pNode= s.pop()) != NULL)   
  622.             {
  623.                 cout << “[“ << pNode>mElement<<“]”                    \
  624.                     <<” Height:” << pNode>mHeigh                        \
  625.                     <<” Left:” << (SAFE_CALL(pNode>mpLeft)>mHeigh)    \
  626.                     <<” Rigth:”<< (SAFE_CALL(pNode>mpRight)>mHeigh)    \
  627.                     <<” bala:” << Balance(pNode) << endl;
  628.             }
  629.         return true;
  630.     }
  631.     #include <fstream>
  632.     using namespace std;
  633.     //把AVL树的信息丰收放到文件中
  634.     template <typename T>
  635.     void AVLTree<T>::saveAVLTreeToFile(const char* pFileName)
  636.     {
  637.         if (!pFileName) return;
  638.         FILE* pFile = fopen(pFileName,“w”);
  639.         if (!pFile)
  640.         {
  641.             cout << “open file failed.” << endl ;
  642.             return ;
  643.         }
  644.         char tmpBuf[512] = {0};
  645.         Stack<TreeNode<T>*> s;
  646.         this>inorderTravel(s);
  647.         sprintf(tmpBuf,“TreeSize: %d\r\n”,s.size());
  648.         fwrite(tmpBuf,strlen(tmpBuf),1,pFile);
  649.         TreeNode<T>* pNode = NULL;
  650.         int iMaxHeigh = 0;
  651.         while ((pNode= s.pop()) != NULL)   
  652.         {
  653.             if (pNode>mHeigh > iMaxHeigh)
  654.             {
  655.                 iMaxHeigh = pNode>mHeigh;
  656.             }
  657.             sprintf(tmpBuf,“[%d]–Hegigh:%d–Left:%d–Right:%d–Bala:%d\r\n”,
  658.                 pNode>mElement,
  659.                 pNode>mHeigh,
  660.                 (SAFE_CALL(pNode>mpLeft)>mHeigh),
  661.                 (SAFE_CALL(pNode>mpRight)>mHeigh),
  662.                 Balance(pNode));
  663.             fwrite(tmpBuf,strlen(tmpBuf),1,pFile);           
  664.         }
  665.         sprintf(tmpBuf,“iMaxHeigh: %d\r\n”,iMaxHeigh);
  666.         fwrite(tmpBuf,strlen(tmpBuf),1,pFile);   
  667.         fclose(pFile);
  668.         pFile = NULL;
  669.     }   
  670. }
  671. #endif

/////////******************************测试函数*****************************************///////////////////////

  1. #include <stdexcept>
  2. #include <typeinfo>
  3. #include <iostream>
  4. #include <fstream>
  5. using namespace std;
  6. #include “AVLTree.h”
  7. #include “Stack.h”
  8. #include “Queue.h”
  9. using namespace _AVL_Tree_;
  10. #include <time.h>
  11. #define ARRY_SIZE        1000
  12. int main(int argc,char** argv)
  13. {
  14.     AVLTree<int> tree;
  15. //    int arr[]    = {1,2,3};//RR
  16. //     int arr[]    = {3,2,1};//LL
  17. //    int arr[]    = {2,4,3};//RL
  18. //     int arr[]    = {4,2,3};//LR
  19. //     int arr[]    = {10,5,3,7,6,8,12,54,11};    //删除8后,还要再次平衡处理右子树
  20. //     int arr[]    = {100,50,30,70,60,80,120,540,110,51,75,112,85,78,71};    //删除 后,还要再次平衡处理左子树85,71,78,79
  21.     int arr[ARRY_SIZE] = {0};
  22.     srand((unsigned int)time(NULL));
  23.     for (int i = 0; i < ARRY_SIZE; i++)
  24.     {
  25.         arr[i] = (rand() % ARRY_SIZE) + 1;
  26.     }
  27.     size_t size = sizeof(arr) / sizeof(int);
  28.    
  29.      for (size_t i = 0; i < size; i++)
  30.      {
  31.          tree.insert(arr[i]);
  32.      }
  33.     cout << “Befor Inorder:”;
  34.     tree.inorderTravel();
  35.     cout << “\nBefor Preorder:”;
  36.     tree.prevorederTravel();
  37.     tree.saveAVLTreeToFile(“AVLResult.txt”);
  38.     cout << “\r\nAVLTree Result writes in file AVLResult.txt.” << endl;
  39.     getchar();
  40.     return 0;
  41. }

 

///////////////*****************************C++实现栈***************************************///////////////////////////////////////////

  1. //Stack.h
  2. //双链表栈数据结构C++模块的实现
  3. //理论知识参考《数据结构(C语言版)严慰明》
  4. #ifndef _STACK_H_
  5. #define _STACK_H_
  6. #include <iostream>
  7. using namespace std;
  8. namespace _STACK_
  9. {
  10. //栈中的元素
  11. template <typename T>
  12. class StackNode
  13. {
  14. public:
  15.   StackNode()
  16.   {
  17.    this>mElement = 0;
  18.    this>mpNext = NULL;
  19.    this>mpPrev = NULL;
  20.   }
  21.  
  22.   ~StackNode()
  23.   {
  24.    this>mElement = 0;
  25.    this>mpNext = NULL;
  26.    this>mpPrev = NULL;
  27.   }
  28.  
  29.   T& getElement(void)
  30.   {
  31.    return mElement;
  32.   }
  33.  
  34.   //重载“<<“操作符,以便对栈节点输出,注意以friend重载“<<”操作符要加上“<>”
  35.   friend ostream& operator << <>(ostream& ost,StackNode<T>& src)
  36.   {
  37.    ost << src.mElement;
  38.    return ost;
  39.   }
  40.  
  41. //protected:
  42.   T mElement; //存放的数据
  43.   StackNode<T>* mpNext; //指向后继节点指针
  44.   StackNode<T>* mpPrev; //指向前驱节点指针
  45.   template <typename T>
  46.   friend class Stack;
  47. };
  48. template <typename T>
  49. class Stack
  50. {
  51. public:
  52.   Stack();
  53.   ~Stack();
  54.   bool push(const T& element);
  55.   T pop(void);
  56.   bool isEmpty(void);
  57.   bool clear(void);
  58.   int size();
  59.   friend ostream& operator<< <>(ostream& ost,Stack<T>& src);
  60. protected:
  61.   StackNode<T>* createNode(const T& element);
  62. protected:
  63.   StackNode<T>* mpHead;
  64.   StackNode<T>* mpTop;
  65. };
  66. template <typename T>
  67. Stack<T>::Stack()
  68. {
  69.   T i = T();
  70.   //创建一个带有头节点的双链栈,这个节点不存入任何数据
  71.   this>mpHead = this>createNode(i);
  72.   this>mpTop = this>mpHead;
  73. }
  74. template <typename T>
  75. Stack<T>::~Stack()
  76. {
  77.   this>clear();
  78.   delete this>mpHead;
  79.   this>mpHead = NULL;
  80.   this>mpTop = NULL;
  81. }
  82. template <typename T>
  83. StackNode<T>* Stack<T>::createNode(const T& element)
  84. {
  85.   StackNode<T>* pNode = new StackNode<T>;
  86.   if (pNode)
  87.   {
  88.    pNode>mElement = element;
  89.    pNode>mpNext = NULL;
  90.    pNode>mpPrev = NULL;
  91.   }
  92.   return pNode;
  93. }
  94. template <typename T>
  95. bool Stack<T>::push(const T& element)
  96. {
  97.   StackNode<T>* pNode = createNode(element);
  98.   if(this>mpHead>mpNext == NULL)
  99.   {
  100.    this>mpHead>mpNext = pNode;
  101.    pNode>mpPrev = this>mpHead;
  102.   }
  103.   else
  104.   {
  105.    this>mpTop>mpNext = pNode;
  106.    pNode>mpPrev = this>mpTop;
  107.   }
  108.   this>mpTop = pNode;
  109.   return true;
  110. }
  111. template <typename T>
  112. T Stack<T>::pop(void)
  113. {
  114.   if (this>mpTop != this>mpHead)
  115.   {
  116.    StackNode<T>* pNode = this>mpTop;
  117.    this>mpTop = this>mpTop>mpPrev;
  118.    T elem = pNode>mElement;
  119.    pNode >mpNext = pNode>mpPrev = NULL;
  120.    delete pNode;
  121.    pNode = NULL;
  122.    return elem;
  123.   }
  124.   return (T)0;
  125. }
  126. template <typename T>
  127. bool Stack<T>::isEmpty(void)
  128. {
  129.   return (this>mpHead == this>mpTop);
  130. }
  131. template <typename T>
  132. bool Stack<T>::clear(void)
  133. {
  134.   StackNode<T>* pNode = this>mpTop;
  135.   while((pNode = this>mpTop) != this>mpHead)
  136.   {
  137.    this>mpTop =pNode>mpPrev;
  138.    pNode>mpNext = NULL;
  139.    pNode>mpPrev = NULL;
  140.    delete pNode;
  141.    pNode = NULL;
  142.   }
  143.   return true;
  144. }
  145. template <typename T>
  146. int Stack<T>::size()
  147. {
  148.   int iCount = 0;
  149.   StackNode<T>* pNode = this>mpTop;
  150.   while(pNode != this>mpHead)
  151.   {
  152.    iCount++;
  153.    pNode = pNode>mpPrev;
  154.   }
  155.   return iCount;
  156. }
  157. template <typename T>
  158. ostream& operator<< <>(ostream& ost,Stack<T>& src)
  159. {
  160.   StackNode<T>* pNode = src.mpTop;
  161.   while( src.mpHead)
  162.   {
  163.    ost << *pNode << ” “;
  164.    pNode = pNode>mpPrev;
  165.   }
  166.   return ost;
  167. }
  168. }
  169. #endif

 

///////////////////////***************************************C++实现队列*********************************////////////////////////////////////////////////

  1. //Queue.h
  2. //双链表队列数据结构C++模块的实现
  3. //理论知识参考《数据结构(C语言版)严慰明》
  4. #ifndef _QUEUE_H_
  5. #define _QUEUE_H_
  6. namespace _QUEUE_
  7. {
  8.     //队列中的数据元素
  9.     template <typename T>
  10.     class QueueNode
  11.     {
  12.     public:
  13.         QueueNode()
  14.         {
  15.             this>mElement    = 0;
  16.             this>mpNext = this>mpPrev    = NULL;
  17.         }
  18.         T                mElement;
  19.         QueueNode<T>*    mpNext;
  20.         QueueNode<T>* mpPrev;
  21.     };
  22.     template <typename T>
  23.     class Queue
  24.     {
  25.     public:
  26.         Queue()
  27.         {
  28.             QueueNode<T> * pNode = new QueueNode<T>;
  29.             pNode>mElement = T(1);
  30.             pNode>mpNext = pNode>mpPrev = NULL;
  31.             this>mpHead = this>mpTail = pNode;
  32.         }
  33.         ~Queue()
  34.         {
  35.             this>clear();
  36.             delete this>mpHead;
  37.             this>mpHead = this>mpTail = NULL;
  38.         }
  39.         bool insert(T element);
  40.         T    front();
  41.         T    back();
  42.         bool isEmpty(void);
  43.         bool clear(void);
  44.         int size();
  45.         friend ostream& operator<< <>(ostream& ostr,const Queue<T>& q);
  46.     private:
  47.         QueueNode<T>* mpHead;
  48.         QueueNode<T>* mpTail;
  49.     };
  50.     template <typename T>
  51.     bool Queue<T>::insert(T element)
  52.     {
  53.         QueueNode<T> * pNode = new QueueNode<T>;
  54.         if (pNode == NULL)    return false;
  55.         pNode>mElement    = element;
  56.         this>mpTail>mpNext = pNode;
  57.         pNode>mpPrev = this>mpTail;
  58.         this>mpTail = this>mpTail>mpNext;
  59.         return true;
  60.     }
  61.     template <typename T>
  62.     T    Queue<T>::front()
  63.     {
  64.         T element = T();
  65.         QueueNode<T>* pNode = NULL;
  66.         if (!this>isEmpty())
  67.         {
  68.             pNode = this>mpHead>mpNext;
  69.             element = pNode>mElement;
  70.             this>mpHead >mpNext = pNode>mpNext;
  71.             if (pNode>mpNext)
  72.                 pNode>mpNext>mpPrev = this>mpHead;
  73.             if (pNode == this>mpTail)
  74.                 this>mpTail = this>mpHead;
  75.             delete pNode;
  76.         }
  77.         return element;
  78.     }
  79.     template <typename T>
  80.     T    Queue<T>::back()
  81.     {
  82.         T element = T();
  83.         QueueNode<T>* pNode = NULL;
  84.         if (!this>isEmpty())
  85.         {
  86.             pNode = this>mpTail;
  87.             element = pNode>mElement;
  88.             this>mpTail = this>mpTail>mpPrev;
  89.             this>mpTail>mpNext = NULL;
  90.             delete pNode;
  91.         }
  92.         return element;
  93.     }
  94.     template <typename T>
  95.     bool Queue<T>::isEmpty(void)
  96.     {
  97.         return (this>mpTail == this>mpHead);
  98.     }
  99.     template <typename T>
  100.     bool Queue<T>::clear(void)
  101.     {
  102.         while (!this>isEmpty())
  103.             this>back();
  104.         return true;
  105.     }
  106.     template <typename T>
  107.     int Queue<T>::size()
  108.     {
  109.         int iCount = 0;
  110.         if (!this>isEmpty())
  111.         {
  112.             QueueNode<T>* pNode = this>mpTail;
  113.             while (pNode != this>mpHead)
  114.             {
  115.                 iCount++;
  116.                 pNode = pNode>mpPrev;
  117.             }
  118.         }
  119.         return iCount;
  120.     }
  121.     template <typename T>
  122.     ostream& operator<< <>(ostream& ostr,const Queue<T>& q)
  123.     {
  124.         QueueNode<T>* pNode = q.mpHead>mpNext;
  125.         while (pNode != NULL)
  126.         {
  127.             ostr << pNode>mElement << “,”;
  128.             pNode = pNode>mpNext;
  129.         }
  130.         return ostr;
  131.     }
  132. }
  133. #endif

 

 

    原文作者:AVL树
    原文地址: https://blog.csdn.net/gwbin198808/article/details/8700253
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞