输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
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
要求不能创建任何新的结点,只调整指针的指向。
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
};
思路:1:构造二叉查找树;
2:中序遍历二叉查找树,因此结点按从小到大顺序访问,假设之前访问过的结点已经调整为一个双向链表,那么只需要将当前结点连接至双向链表的最后一个结点即 可,访问完后,双向链表也就调整完了
#include <iostream>
#include <string.h>
using namespace std;
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
};
BSTreeNode *head=NULL,*Iphin=NULL;
void newset(BSTreeNode *&rode,int val) //建立二叉树,注意由于下面指针值会发生改变,所以使用引用传递
{
if(rode==NULL)
{
BSTreeNode *Rode=new BSTreeNode();
Rode->m_nValue=val;
Rode->m_pLeft=NULL;
Rode->m_pRight=NULL;
rode=Rode;
}
else if(rode->m_nValue>val)
{
newset(rode->m_pLeft,val);
}
else if(rode->m_nValue<val)
{
newset(rode->m_pRight,val);
}
}
void convert(BSTreeNode *&rode) //调整节点指针
{
rode->m_pLeft=Iphin; //使当前结点的左指针指向双向链表中最后一个结点
if(Iphin==NULL)
{
head=rode;
}
else
Iphin->m_pRight=rode; //使双向链表中最后一个结点的右指针指向当前结点
Iphin=rode; //将当前结点设为双向链表中最后一个结点
cout<<rode->m_nValue<<" ";
}
void find(BSTreeNode *rode) //中序遍历查找二叉树,注意这里是指针传递,而上面是引用传递
{
if(rode==NULL)
return ;
if(rode->m_pLeft!=NULL)
find(rode->m_pLeft);
convert(rode);
if(rode->m_pRight!=NULL)
find(rode->m_pRight);
}
int main()
{
BSTreeNode *pRoot=NULL;
newset(pRoot,10);
newset(pRoot,6);
newset(pRoot,14);
newset(pRoot,4);
newset(pRoot,8);
newset(pRoot,12);
newset(pRoot,16);
find(pRoot);
return 0;
}