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

☆樱花仙子☆ 提交于 2019-12-18 18:58:12

数据结构实验之求二叉树后序遍历和层次遍历
Time Limit: 1000 ms Memory Limit: 65536 KiB

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

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

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

Sample Input
2
abdegcf
dbgeafc
xnliu
lnixu
Sample Output
dgebfca
abcdefg
linux
xnuli

实现代码

#include <bits/stdc++.h>
using namespace std;

char s1[55],s2[55];
typedef struct node
{
char data;
struct node *l,*r;
} tree;
tree *creat(int n,char *s1,char *s2)
{
int i;
if(n==0)
return NULL;
tree *root;
root = new tree;
root->data=s1[0];
for(i=0; i<n; i++)
{
if(s2[i]==s1[0])
break;
}
root->l=creat(i,s1+1,s2);
root->r=creat(n-i-1,s1+i+1,s2+i+1);
return root;
};
void hou(tree *root)
{
if(root!=NULL)
{
hou(root->l);
hou(root->r);
printf("%c",root->data);
}
}
void cc(tree *root)
{
int in=0,out=0;
tree *num[66];
num[in++]=root;
while(in>out)
{
if(num[out])
{
printf("%c",num[out]->data);
num[in++]=num[out]->l;
num[in++]=num[out]->r;
}
out++;
}
}
int main()
{
int t,n;
scanf("%d",&t);
while(t–)
{
scanf("%s",s1);
scanf("%s",s2);
n=strlen(s1);
tree *root;
root=creat(n,s1,s2);
hou(root);
printf("\n");
cc(root);
printf("\n");
}
return 0;
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!