• 把二元查找树转变成排序的双向链表


     1 #include <iostream.h>
     2 
     3 struct BSTreeNode
     4 {
     5     int m_nValue;
     6     struct BSTreeNode *m_pLeft;
     7     struct BSTreeNode *m_pRight;
     8 };
     9 
    10 void addBSTreeNode(BSTreeNode *&pCurrent,int value); //建立二叉排序树
    11 void inOrderBSTree(BSTreeNode *pBSTree); //中序遍历
    12 void convertToDoubleList(BSTreeNode *pCurrent);//转换成双链表
    13 
    14 BSTreeNode *pHead=NULL;//指向双链表的头结点
    15 BSTreeNode *pIndex=NULL;//指向前一个结点
    16 
    17 int main()
    18 {
    19     BSTreeNode *pRoot=NULL;
    20     addBSTreeNode(pRoot,10);
    21     addBSTreeNode(pRoot,6);
    22     addBSTreeNode(pRoot,14);
    23     addBSTreeNode(pRoot,4);
    24     addBSTreeNode(pRoot,8);
    25     addBSTreeNode(pRoot,12);
    26     addBSTreeNode(pRoot,16);
    27 
    28     inOrderBSTree(pRoot);
    29     return 0;
    30 }
    31 
    32 
    33 void addBSTreeNode(BSTreeNode *&pCurrent,int value)
    34 {
    35     if(pCurrent==NULL)
    36     {
    37         BSTreeNode *pBSTree=new BSTreeNode;
    38         pBSTree->m_nValue=value;
    39         pBSTree->m_pLeft=NULL;
    40         pBSTree->m_pRight=NULL;
    41         pCurrent=pBSTree;
    42     }
    43     else if (pCurrent->m_nValue<value)
    44     {
    45         addBSTreeNode(pCurrent->m_pRight,value);
    46     }
    47     else if (pCurrent->m_nValue>value)
    48     {
    49         addBSTreeNode(pCurrent->m_pLeft,value);
    50     }
    51     else
    52     {
    53         cout<<"node repeated"<<endl;
    54     }
    55 }
    56 
    57 void inOrderBSTree(BSTreeNode *pBSTree)
    58 {
    59     if (NULL==pBSTree)
    60     {
    61         return;
    62     }
    63 
    64     if (NULL!=pBSTree->m_pLeft)
    65     {
    66         inOrderBSTree(pBSTree->m_pLeft);
    67     }
    68 
    69     convertToDoubleList(pBSTree);
    70 
    71     if (NULL!=pBSTree->m_pRight)
    72     {
    73         inOrderBSTree(pBSTree->m_pRight);
    74     }
    75 }
    76 
    77 
    78 void convertToDoubleList(BSTreeNode *pCurrent)
    79 {
    80     pCurrent->m_pLeft=pIndex;
    81 
    82     if (NULL==pIndex)
    83     {
    84         pHead=pIndex;
    85     }
    86 
    87     else
    88     {
    89         pIndex->m_pRight=pCurrent;
    90     }
    91 
    92     pIndex=pCurrent;
    93 
    94     cout<<pCurrent->m_nValue<<" ";
    95 }
  • 相关阅读:
    为什么转速环经过pi调节后输出的是电流?
    如何将mysql、php、nginx设置为开机自启动
    rm-rf /*
    2020/4/23-linux中的定时任务详解
    2020/4/20 一键部署服务
    2020/4/20-ansible一键部署nfs
    2020/4/20-backup之rsync
    2020/4/19-linux中/etc/hosts
    2020/4/18-linux中的selinux
    2020/4/18-linux中的iptables
  • 原文地址:https://www.cnblogs.com/Trony/p/2658754.html
Copyright © 2020-2023  润新知