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

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

2017-08-08 16:01 239 查看

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

Time Limit: 1000MS
Memory Limit: 65536KB
SubmitStatistic

Discuss

Problem Description

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

Input

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

Output

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

Example Input

2
abdegcf
dbgeafc
xnliu
lnixu


Example Output

dgebfca
abcdefg
linux
xnuli


#include <iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
typedef struct BiTNode
{
char data;
struct BiTNode*left,*right;
}BiTNode,*BiTree;
BiTree bulid(int n,char *str1,char *str2) // 已知先序和中序,还原二叉树
{
if(n==0) // 序 列   长 度
return NULL;
char *p;
BiTree T;
T=(BiTree)malloc(sizeof(BiTNode));
T->data=str1[0]; //寻 找根 节点,新的根节点为前序遍历str1的第一 个
for(p=str2;p!=" ";p++)  //p!='\0',寻找新的根节点在中序遍历str2中的位置
{
if(*p == str1[0])  //
break;
}
int k=p-str2;
T->left=bulid(k,str1+1,str2);  //左子树的长度,左子树在前序遍历str1中的开始位置,左子树在中 遍历 st2中的开始位置

T->right=bulid(n-k-1,str1+k+1,p+1);  //右子树的长度,右子树在前序遍历str1中的开始位置,右子树在中序遍历 st2中的开始位置
return T;
};
void hou(BiTree T)
{
if(T!=NULL)
{
hou(T->left);
hou(T->right);
cout<<T->data;
}
}
void ceng(BiTree T)
{
int i=0,j=1;
BiTree q[100];
q[0]=T;
while(i<j)
{
if(q[i]) //判断 q[i]是否为空
{

q[j++]=q[i]->left; //入 队
q[j++]=q[i]->right; //入 队
cout<<q[i]->data;
}
i++;  //出队
}
}
int main()
{
int n;
char str1[100],str2[100];
BiTree t;
t=(BiTree)malloc(sizeof(BiTNode));
cin>>n;
while(n--)
{
cin>>str1>>str2;
int len=strlen(str1);
t=bulid(len,str1,str2);
hou(t);
cout<<"\n";
ceng(t);
cout<<"\n";
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: