首页 > 学院 > 开发设计 > 正文

求二叉树的先序遍历 sdut 1489

2019-11-08 00:58:39
字体:
来源:转载
供稿:网友

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

2 dbgeafc dgebfca lnixu linux

Example Output

abdegcf xnliu


#include <stdio.h>#include <string.h>#include <stdlib.h>char mid[60],h[60];typedef struct node{ char data; struct node*l,*r;}tree;tree *creat(int len,char *mid,char *h){ if(len<=0) return NULL; int i,j; tree *t; t=(tree *)malloc(sizeof(tree)); t->data=h[len-1]; for(i=0;i<len;i++) { if(mid[i]==h[len-1]) break; } t->l=creat(i,mid,h); t->r=creat(len-i-1,mid+i+1,h+i); return t;}void show(tree *t){ if(t) { printf("%c",t->data ); show(t->l); show(t->r); }}int main(int argc, char const *argv[]){ int t; scanf("%d",&t); while(t--) { memset(mid,0,sizeof(mid)); memset(h,0,sizeof(h)); scanf("%s %s",mid,h); int len=strlen(mid); tree *root; root=creat(len,mid,h); show(root); printf("/n"); } return 0;}
上一篇:PAT 1048

下一篇:HDU1232 畅通工程

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表