#include <iostream>
#include <stdio.h>
using namespace std;
typedef struct _TNode{
int item;
_TNode *lchild;
_TNode *rchild;
_TNode():item(0),lchild(NULL),rchild(NULL){}
}TNode;
typedef struct _LNode{
int item;
_LNode *pre;
_LNode *pos;
_LNode():item(0),pre(NULL),pos(NULL){}
_LNode(int x):item(x),pre(NULL),pos(NULL){}
}LNode;
LNode *getLNode(int elem)
{
LNode * p = new LNode;
p->item = elem;
return p;
}
TNode *getTNode(int elem)
{
TNode * p = new TNode;
p->item = elem;
return p;
}
void insertlist(LNode *centrol, LNode *other, bool right)
{
if(right)
{
if(centrol->pos)
centrol->pos->pre = other;
other->pre = centrol;
other->pos = centrol->pos;
centrol->pos = other;
}
else
{
if(centrol->pre)
centrol->pre->pos = other;
other->pos = centrol;
other->pre= centrol->pre;
centrol->pre = other;
}
}
void insertchild(LNode *centrol, TNode * parent)
{
if(parent->lchild)
{
LNode *pl = getLNode(parent->lchild->item);
insertlist(centrol,pl,false);
insertchild(pl,parent->lchild);
}
if(parent->rchild)
{
LNode *pr = getLNode(parent->rchild->item);
insertlist(centrol,pr,true);
insertchild(pr,parent->rchild);
}
}
LNode *exchange(TNode *root)
{
// insert root node
LNode *Lroot = getLNode(root->item);
// insert others by subapis
insertchild(Lroot, root);
// get most left node by root
while(Lroot->pre)
{
Lroot=Lroot->pre;
}
return Lroot;
}
void _constructTree(TNode * par,TNode *child)
{
//cout<<"par : "<<par->item<<" child: "<<child->item;
if(par->item<child->item)
{
//cout<<" r"<<endl;
par->rchild = child;
}
else
{
par->lchild = child;
//cout<<" l"<<endl;
}
}
TNode *constructTree(int *p, int len)
{
TNode *root = getTNode(*p);
TNode *par = root;
for(int k = 1;k<len;++k)
{
TNode *tmp = getTNode(*(p+k));
bool left = false;
bool right = false;
par = root;
while((left = tmp->item > par->item && par->rchild)
|| (right = tmp->item < par->item && par->lchild))
{
if(left)
par = par->rchild;
else if(right)
par = par->lchild;
else
{
break;
}
}
_constructTree(par, tmp);
}
return root;
}
void pt(TNode * node)
{
cout<<"par "<<node->item<<endl;
if(node->lchild)
{
cout<<"l ";
pt(node->lchild);
}
if(node->rchild)
{
cout<<"r ";
pt(node->rchild);
}
}
void DestroyTree(TNode * node)
{
//cout<<"par "<<node->item<<endl;
TNode * tmp = node;
if(node->lchild)
{
//cout<<"l ";
DestroyTree(node->lchild);
}
if(node->rchild)
{
//cout<<"r ";
DestroyTree(node->rchild);
}
delete tmp;
}
void pl(LNode * node)
{
while(node)
{
cout<<node->item<<" ";
node = node->pos;
}
}
void destroyList(LNode *node)
{
while(node)
{
//cout<<node->item<<" ";
LNode * tmp = node;
node = node->pos;
delete tmp;
}
}
int main()
{
int a[]={10,8,12,6,9,11,13,5,7};
TNode *root = constructTree(a, sizeof(a)/sizeof(int));
//pt(root);
//cout<<"~~"<<endl;
LNode *lh = exchange(root);
pl(lh);
destroyList(lh);
DestroyTree(root);
system("pause");
return 0;
}
把二元查找树转变成排序的双向链表
最新推荐文章于 2021-12-20 10:05:56 发布