输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ /
6 14
/ / / /
4 8 12 16
转换成双向链表
要求不能创建任何新的结点,只调整指针的指向。
10
/ /
6 14
/ / / /
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
#include <iostream>
using namespace std;
struct BTSTree
{
int value;
BTSTree *m_left;
BTSTree *m_right;
};
BTSTree *index=nullptr;
BTSTree *head=nullptr;
void makelist(BTSTree *ptr);
//构建二叉查找树
void addBTSTree(int value,BTSTree *&ptr)
{
if (ptr==nullptr)
{
BTSTree *currentptr=new BTSTree();
currentptr->value=value;
currentptr->m_left=nullptr;
currentptr->m_right=nullptr;
ptr=currentptr;
}
else
{
if (value>ptr->value)
{
addBTSTree(value,ptr->m_right);
}
else
{
addBTSTree(value,ptr->m_left);
}
}
}
//中序遍历
void midreserch(BTSTree *ptr)
{
if (ptr==nullptr)
{
return;
}
if (ptr->m_left!=nullptr)
{
midreserch(ptr->m_left);
}
makelist(ptr);
if (ptr->m_right!=nullptr)
{
midreserch(ptr->m_right);
}
}
//链表
void makelist(BTSTree *ptr)
{
ptr->m_left=index;
if (index!=nullptr)
{
index->m_right=ptr;
}
else
{
head=ptr;
}
index=ptr;
cout<<index->value<<endl;
}
int main()
{
BTSTree *root=nullptr;
addBTSTree(12,root);
addBTSTree(5,root);
addBTSTree(6,root);
addBTSTree(11,root);
addBTSTree(9,root);
addBTSTree(14,root);
addBTSTree(8,root);
midreserch(root);
return 0;
}