求二叉树的先序遍历

素颜马尾好姑娘i 2022-07-12 02:10 232阅读 0赞

Problem Description

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

Input

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

Output

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

Example Input

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

Example Output

  1. abdegcf
  2. xnliu
  3. #include<stdio.h>
  4. #include<string.h>
  5. #include<stdlib.h>
  6. typedef struct node
  7. {
  8. char data;
  9. struct node *lc,*rc;
  10. }bitree;
  11. bitree * create(int zlen,char hst[51],char zst[51])
  12. {
  13. int i;
  14. bitree *t;
  15. if(zlen<=0)
  16. return NULL;
  17. t=(bitree *)malloc(sizeof(bitree));
  18. t->data=hst[0];
  19. for(i=0;i<zlen;i++)
  20. {
  21. if(zst[i]==hst[0])
  22. break;
  23. }
  24. t->lc=create(i,hst-zlen+i,zst);
  25. t->rc=create(zlen-i-1,hst-1,zst+i+1);
  26. return t;
  27. }
  28. void preshow(bitree * tree)
  29. {
  30. bitree * t;
  31. t=tree;
  32. if(t)
  33. {
  34. printf("%c",t->data);
  35. preshow(t->lc);
  36. preshow(t->rc);
  37. }
  38. }
  39. int main()
  40. {
  41. int t,zlen,hlen;
  42. char hst[51],zst[51];
  43. bitree * tree;
  44. scanf("%d",&t);
  45. while(t--)
  46. {
  47. scanf("%s%s",zst,hst);
  48. zlen=strlen(zst);
  49. hlen=strlen(hst);
  50. tree=create(zlen,hst+hlen-1,zst);
  51. preshow(tree);
  52. printf("\n");
  53. }
  54. return 0;
  55. }

发表评论

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

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

相关阅读

    相关

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

    相关

      二叉树不同于列表、链表、栈、队列这些线性结构,也不同于图这种非线性结构,它属于半线性结构。我们在搞二叉树的时候不要从轮子造起,而要善于引用此前的工作成果,转化成以前已经玩烂