数据结构实验之求二叉树后序遍历跟层次遍历
数据结构实验之求二叉树后序遍历和层次遍历
数据结构实验之求二叉树后序遍历和层次遍历
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历。
输入
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。
输出
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列
示例输入
2 abdegcf dbgeafc xnliu lnixu
示例输出
dgebfca abcdefg linux xnuli
提示
来源
ma6174
示例程序
- #include<stdio.h>
- #include<string.h>
- char st1[100],st2[100];
- struct node
- {
- char c;
- struct node *lnext,*rnext;
- };
- void build(int n,char *s1,char *s2,struct node *&p)
- {
- if(n<=0)
- return ;
- p=new node;
- p->c=s1[0];
- int num=strchr(s2,s1[0])-s2;
- build(num,s1+1,s2,p->lnext);
- build(n-num-1,s1+num+1,s2+num+1,p->rnext);
- }
- void last(struct node *t)
- {
- if(t==NULL)
- return ;
- else
- {
- last(t->lnext);
- last(t->rnext);
- printf("%c",t->c);
- }
- }
- void cengci(struct node *t)
- {
- int s=0,e=0;
- struct node *que[100100],*now,*tmp;
- que[s++]=t;
- while(s>e)
- {
- now=que[e++];
- printf("%c",now->c);
- tmp=now;
- if(tmp->lnext!=NULL)
- que[s++]=tmp->lnext;
- if(tmp->rnext!=NULL)
- que[s++]=tmp->rnext;
- }
- }
- int main()
- {
- int n;
- scanf("%d%*c",&n);
- while(n--)
- {
- scanf("%s%s",st1,st2);
- int len=strlen(st1);
- struct node *q;
- build(len,st1,st2,q);
- last(q);
- printf("\n");
- cengci(q);
- printf("\n");
- }
- return 0;
- }
版权声明:本文为博主原创文章,未经博主允许不得转载。