求二叉树的先序遍历

亦凉 2024-02-18 22:31 128阅读 0赞

求二叉树的先序遍历

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

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

Input

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

Output

输出二叉树的先序遍历序列

Sample Input

  1. 2
  2. dbgeafc
  3. dgebfca
  4. lnixu
  5. linux

Sample Output

  1. abdegcf
  2. xnliu

Hint

Source

GYX

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. struct node
  5. {
  6. char num;
  7. struct node *l,*r;
  8. };
  9. struct node *kk(char j[],int n,char i[])
  10. {
  11. if(n<=0)
  12. return NULL;
  13. struct node *root;
  14. root=(struct node *)malloc(sizeof(struct node));
  15. root->num=j[n-1];
  16. int v;
  17. for(v=0;v<n;v++)
  18. if(i[v]==j[n-1])break;
  19. root->l=kk(j,v,i);
  20. root->r=kk(j+v,n-v-1,i+v+1);
  21. return root;
  22. };
  23. void zz(struct node *head)
  24. {
  25. if(head==NULL)
  26. return ;
  27. printf("%c",head->num);
  28. zz(head->l);
  29. zz(head->r);
  30. }
  31. int main()
  32. {
  33. int a,b;
  34. char i[1000],j[1000];
  35. struct node *head;
  36. scanf("%d",&b);
  37. while(b--)
  38. {
  39. scanf("%s %s",i,j);
  40. a=strlen(i);
  41. head=kk(j,a,i);
  42. zz(head);
  43. printf("\n");
  44. }
  45. return 0;
  46. }

发表评论

表情:
评论列表 (有 0 条评论,128人围观)

还没有评论,来说两句吧...

相关阅读

    相关

    前两天面试,看见了个笔试题,关于二叉树的,今天算是把自己的一点理解写下来吧。 今天看网文,才想起来,二叉树的先序遍历、中序遍历、后序遍历, 遍历顺序都是