您的位置:首页 > 其它

重建二叉树与二叉树的层次遍历

2014-07-20 13:27 155 查看

数据结构实验之求二叉树后序遍历和层次遍历


TimeLimit:1000msMemorylimit:65536K有疑问?点这里^_^

题目描述

已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历。

输入

输入数据有多组,第一行是一个整数t(t<1000),代表有t组测试数据。每组包括两个长度小于50的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。

输出

每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列

示例输入

2
abdegcf
dbgeafc
xnliu
lnixu


示例输出

dgebfca
abcdefg
linux
xnuli


#include<stdio.h>
#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>
usingnamespacestd;
typedefstructnode
{
chardata;
node*lch,*rch;
}btree,*bt;
charpre[55],ins[55];
voidbuild(bt&T,char*pre,char*ins,intn)//根据先序和中序重建二叉树
{
if(n<=0)T=NULL;
else
{
intk=strchr(ins,pre[0])-ins;
T=newbtree;
T->data=pre[0];
build(T->lch,pre+1,ins,k);
build(T->rch,pre+k+1,ins+k+1,n-k-1);
}
}
voidlast(btT)//后序遍历
{
if(T)
{
last(T->lch);
last(T->rch);
cout<<T->data;

}
}
voidlevel(btT)//层次遍历(BFS)
{
queue<btree>Q;
Q.push(*T);
while(!Q.empty())
{
btreenext=Q.front();
Q.pop();
cout<<next.data;
if(next.lch)Q.push(*(next.lch));
if(next.rch)Q.push(*(next.rch));
}
}
intmain()
{
btroot;
intn;
cin>>n;
getchar();
while(n--)
{
cin>>pre>>ins;
build(root,pre,ins,strlen(pre));
last(root);
cout<<endl;
level(root);
cout<<endl;
}
return0;
}


[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: