您的位置:首页 > 其它

【转】100题题1解——把二元查找树转变成排序的双向链表

2011-04-27 20:28 471 查看
参见原文: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐