/*--------------------------------
1.把二元查找树转变成排序的双向链表
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ /
6 14
/ / / /
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
首先我们定义的二元查找树 节点的数据结构如下:
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
};
*/
#include<iostream>
#include<cstdio>
using namespace std;
typedef struct BSTreeNode
{
int m_nValue; // value of node
struct BSTreeNode *m_pLeft; // left child of node
struct BSTreeNode *m_pRight; // right child of node
}BSTreeNode;
typedef BSTreeNode DoubleList;
DoubleList *pHead=NULL;
DoubleList *pTail=NULL;
void addBSTNode(BSTreeNode *&pCurrent,int value);
void convertToDoubleList(BSTreeNode *pCurrent);
void inorderTraverse(BSTreeNode *&pCurrent);
void addBSTNode(BSTreeNode *&pCurrent,int value)
{
if(pCurrent==NULL)
{
BSTreeNode *pNew=new BSTreeNode();
pNew->m_nValue=value;
pNew->m_pLeft=NULL;
pNew->m_pRight=NULL;
pCurrent=pNew; /*这条语句非常重要,当创建的一个新的节点,就需要把它连接到合适的位置(即成为其父节点的左孩子或右孩子)
此时pCurrent作为右值是指向它的孩子节点的指针(是左孩子还是右孩子取决于调用时的实参),而作为左值就代表
其存放孩子节点位置的存储区域*/
}
else
{
if(value > pCurrent->m_nValue)
addBSTNode(pCurrent->m_pRight,value);
else if(value < pCurrent->m_nValue)
addBSTNode(pCurrent->m_pLeft,value);
else
cout<<"输入的数字产生重复"<<endl;
}
}
void convertToDoubleList(BSTreeNode *pCurrent)
{
pCurrent->m_pLeft=pTail;
if(pTail==NULL)
{
pHead=pCurrent;
pCurrent->m_pRight=NULL;
}
else
{
pTail->m_pRight=pCurrent;
}
pTail=pCurrent;
cout<<pCurrent->m_nValue<<endl;
}
void inorderTraverse(BSTreeNode *&pCurrent)
{
if(pCurrent==NULL)
return;
if(pCurrent->m_pLeft!=NULL)
inorderTraverse(pCurrent->m_pLeft);
convertToDoubleList(pCurrent);
if(pCurrent->m_pRight!=NULL)
inorderTraverse(pCurrent->m_pRight);
}
int main()
{
BSTreeNode *pRoot=NULL;
addBSTNode(pRoot, 10);
addBSTNode(pRoot, 4);
addBSTNode(pRoot, 6);
addBSTNode(pRoot, 8);
addBSTNode(pRoot, 12);
addBSTNode(pRoot, 14);
addBSTNode(pRoot, 15);
addBSTNode(pRoot, 16);
inorderTraverse(pRoot);
return 0;
}
把二元查找树转变成排序的双向链表
最新推荐文章于 2016-11-26 13:06:03 发布