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

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

2015-07-30 15:27 459 查看

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


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

题目描述

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

输入

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

输出

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

示例输入

2
abdegcf
dbgeafc
xnliu
lnixu


示例输出

dgebfca
abcdefg
linux
xnuli


裸的二叉树,主要是建树与层次遍历


[code]#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
usingnamespacestd;
typedefstructnode
{
chard;
structnode*l,*r;
}tree;
charpre[64],mid[64];
queue<tree*>q;

tree*bu(char*pre,char*mid,intlen)//已知前序与中序来建树
{
intk;
if(len<=0)
returnNULL;
tree*head;
head=(tree*)malloc(sizeof(tree));
head->d=*pre;//插入节点
char*p;
for(p=mid;p!=NULL;p++)//找到当前的根节点
if(*p==*pre)
break;//在中序遍历的序列中得到与先序相同的节点
k=p-mid;
head->l=bu(pre+1,mid,k);//递归得到左子树,这里虽说是递归但不好理解,左子树的递归为先序和中序同时的进行递归
head->r=bu(pre+k+1,p+1,len-k-1);//得到右子树
returnhead;
}

voidpos(tree*h)
{
if(h)
{
pos(h->l);
pos(h->r);
printf("%c",h->d);
}

}
voidlor(tree*h)//直接调用队列,分别按从上到下,从左到右的顺序进队,然后依次遍历次
{
if(h!=NULL)
q.push(h);
while(!q.empty())
{
tree*b;
b=q.front();
printf("%c",b->d);
q.pop();
if(b->l)
{
q.push(b->l);
}
if(b->r)
q.push(b->r);
}
}
intmain()
{
intn,m,i,j,k;
cin>>n;
//getchar();
tree*h;
while(n--)
{
cin>>pre;
cin>>mid;
k=strlen(pre);
h=newnode;
h=bu(pre,mid,k);
pos(h);
printf("\n");
lor(h);
printf("\n");
}
return0;
}

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