参见原文:http://blog.csdn.net/proing/archive/2010/12/06/6058724.aspx


// Exereise.cpp    
#include "stdafx.h"  
#include <iostream>  
using namespace std;  
struct BSTreeNode  
{  
    int          m_nValue;   // value of node  
    BSTreeNode  *m_pLeft;    //leftchild ofnode  
    BSTreeNode  *m_pRight;   // right child ofnode  
};  
typedef BSTreeNode DoubleList;  
DoubleList *pHead = NULL;  
DoubleList *pDoubleList = NULL;  
// 创建二元查找树  
void addBSTreeNode(BSTreeNode *& pCurrent, int value)  
{  
    if(NULL == pCurrent)  
    {  
        BSTreeNode * pTree = new BSTreeNode();  
        pTree->m_pLeft = NULL;  
        pTree->m_pRight = NULL;  
        pTree->m_nValue = value;  
        pCurrent = pTree;  
    }  
    else  
    {  
        if(value > pCurrent->m_nValue)  
        {  
            addBSTreeNode(pCurrent->m_pRight,value);  
        }  
        else if(value < pCurrent->m_nValue)  
        {  
            addBSTreeNode(pCurrent->m_pLeft,value);  
        }  
        else  
        {  
            cout<<"Input invalid,there already have the value!"<<endl;  
        }  
    }  
}  
// 二叉树转换成list  
void convertToDoubleList(BSTreeNode * pCurrent)  
{  
    pCurrent->m_pLeft = pDoubleList;  
      
    if (NULL == pDoubleList)  
    {  
        pHead = pCurrent;  
    }  
    else  
    {  
        pDoubleList->m_pRight =pCurrent;  
    }  
    pDoubleList = pCurrent;  
}  
// 遍历二元查找树 中序遍历根节点  
void ergodicBSTree(BSTreeNode * pCurrent)  
{  
    if(NULL == pCurrent)  
        return;  
    else  
    {  
        if(NULL != pCurrent->m_pLeft)  
            ergodicBSTree(pCurrent->m_pLeft);  
        convertToDoubleList(pCurrent);  
        if(NULL != pCurrent->m_pRight)  
            ergodicBSTree(pCurrent->m_pRight);  
    }  
}  
int _tmain(int argc, _TCHAR* argv[])  
{  
    int value;  
    BSTreeNode *pBSTree = NULL;  
    cin>>value;  
    while(-1 != value)  
    {  
        addBSTreeNode(pBSTree,value);  
        cin>>value;  
    }  
    ergodicBSTree(pBSTree);  
    while(pHead)  
    {  
        cout<<pHead->m_nValue<<endl;  
        pHead = pHead->m_pRight;  
    }  
    return 0;  
}  

相关文章:

  • 2021-10-31
  • 2021-07-28
  • 2022-12-23
  • 2021-11-26
  • 2022-03-04
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-25
  • 2022-02-15
  • 2021-08-29
相关资源
相似解决方案