您的位置:首页 > 理论基础 > 数据结构算法

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

2016-08-06 16:20 344 查看


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




Time Limit: 1000ms   Memory limit: 65536K  



题目描述

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


输入

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


输出

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


示例输入

2
abdegcf
dbgeafc
xnliu
lnixu



示例输出

dgebfca
abcdefg
linux
xnuli



提示

前序序列的作用是确定一棵二叉树的根节点,中序序列的作用是确定左、右子树的中序序列(含各自的节点个数)。

层次遍历:先将根节点入队列,在不为空时循环:访问队首节点,若它有左节点,则左节点进队列;若有右节点,则右节点进队列。直到队列为空。

#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
struct Tnode
{
char d;
Tnode *l,*r;
};
Tnode *CreatTree(char pre[],char in[],int len)
{
if(len<=0)
return NULL;
Tnode *p=new Tnode;
p->d=*pre;
int i=0;
for( i=0; i<len; i++)
if(*pre==in[i])        //找到相等的位置
break;
p->l=CreatTree(pre+1,in,i);
p->r=CreatTree(pre+i+1,in+i+1,len-i-1);
return p;
}
void level_order(Tnode *p)  //层次遍历
{
queue<Tnode *>q;
if(p!=NULL)
q.push(p);
while(!q.empty())
{
p=q.front();
cout<<p->d;
q.pop();
if(p->l)
q.push(p->l);
if(p->r)
q.push(p->r);
}
}
void pro_order(Tnode *p)
{
if(p!=NULL)

{
pro_order(p->l);
pro_order(p->r);
cout<<p->d;
}
}
int main()
{
int t;
while(cin>>t)
{
while(t--)
{
char in[60],pre[60];
cin>>pre>>in;
Tnode *Tree=CreatTree(pre,in,strlen(in));
pro_order(Tree);
cout<<endl;
level_order(Tree);
cout<<endl;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: