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

/*--------------------------------
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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值