swust oj 983

时间:2023-03-09 22:09:23
swust oj 983

利用二叉树中序及后序遍历确定该二叉树的先序序列

1000(ms)
10000(kb)
2606 / 4908
已知二叉树的中序和先序遍历可以唯一确定后序遍历、已知中序和后序遍历可以唯一确定先序遍历,但已知先序和后序,却不一定能唯一确定中序遍历。现要求根据输入的中序遍历结果及后序遍历结果,要求输出其先序遍历结果。

输入

第一行为中序序列
第二行为后续序列

输出

输出为遍历二叉树得到的先序序列

样例输入

BFDAEGC
FDBGECA

样例输出

ABDFCEG 
 #include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cstdio>
typedef char Datetype;
using namespace std;
int x; typedef struct link{
Datetype date;
struct link *lchild;
struct link *rchild;
}tree; typedef struct queue{
tree *data;
struct queue *next;
}que; typedef struct {
que *front;
que *rear;
}lin; void Initqueue(lin *&L)
{
L=(lin *)malloc(sizeof(lin));
L->front=L->rear=NULL;
} void destroyed(lin *&L)
{
que *p=NULL,*r=NULL;
p=L->front;
while(p!=NULL)
{
r=p;
p=p->next;
free(r);
}
free(L);
} bool pop(lin *&L, tree *&e)
{
que *p;
if(L->rear==NULL)
return false;
p=L->front;
if(L->rear==L->front)
L->front=L->rear=NULL;
else
L->front=p->next;
e=p->data;
free(p);
return true;
} int empty(lin *&L)
{
return (L->rear==NULL);
} void push(lin *&L,tree *e)
{
que *p;
p = (que *)malloc(sizeof(que));
p->data=e;
p->next=NULL;
if(L->rear==NULL)
{
L->front=p;
L->rear=p;
}
else
{
L->rear->next=p;
L->rear=p;
}
} void creattree(tree *&L)
{
char c;
cin>>c;
if(c=='#')
L=NULL;
else
{
L = (tree *)malloc(sizeof(tree)) ;
L->date=c;
creattree(L->lchild);
creattree(L->rchild);
}
} void find(tree *L)
{
if(L!=NULL)
{
x++;
find(L->rchild);
}
} void destroytree(tree *&L)
{
if(L!=NULL)
{
destroytree(L->lchild);
destroytree(L->rchild);
free(L);
}
} int deep(tree *L)
{
int ldep,rdep,max;
if(L!=NULL)
{
ldep=deep(L->lchild);
rdep=deep(L->rchild);
max=ldep>rdep?ldep+:rdep+;
return max;
}
else
return ;
} void finddegree(tree *&L, int n)
{
if(L!=NULL)
{
if(x<n)
x=n;
finddegree(L->lchild,n);
finddegree(L->rchild,n+);
} } void run(tree *L)
{
tree *p=L;
lin *qu;
Initqueue(qu);
if(L!=NULL)
push(qu,p);
while(!empty(qu))
{
pop(qu,p);
cout<<p->date;
if(p->lchild!=NULL)
push(qu,p->lchild);
if(p->rchild!=NULL)
push(qu,p->rchild);
}
destroyed(qu);
} void displayhou(tree *&L)
{
if(L!=NULL)
{
displayhou(L->lchild);
displayhou(L->rchild);
cout<<L->date;
}
} void displaypre(tree *&L)
{
if(L!=NULL)
{
cout<<L->date;
displaypre(L->lchild);
displaypre(L->rchild);
}
} void creatinpre(tree *&L ,char *in,char *pre,int x)
{
int k=;
char *p;
if(x<=)
{
L=NULL;
return ;
}
L=(tree *)malloc(sizeof(tree));
L->date = *pre;
for(p=in ; p<in+x; p++)
{
if(*p==*pre)
break;
}
k=p-in;
creatinpre(L->lchild,in,pre+,k);
creatinpre(L->rchild,p+,pre+k+,x-k-);
} void creatinhou(tree *&L ,char *in,char *pre,int x)
{
int k=;
char *p;
if(x<=)
{
L=NULL;
return ;
}
L=(tree *)malloc(sizeof(tree));
L->date = *pre;
for(p=in ; p>in-x; p--)
{
if(*p==*pre)
break;
}
k=in-p;
creatinhou(L->rchild,in,pre-,k);
creatinhou(L->lchild,p-,pre-k-,x-k-);
} int main()
{
tree *L = NULL;
x=;
char in[],hou[];
cin>>in;
cin>>hou;
x=strlen(in);
creatinhou(L,in+x-,hou+x-,x);
displaypre(L);
destroytree(L);
return ;
}