求二叉树的先序遍历

╰半夏微凉° 2022-07-12 07:08 235阅读 0赞

Problem Description

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

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

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

2
dbgeafc
dgebfca
lnixu
linux
Example Output

abdegcf
xnliu
Hint

Author

GYX

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. struct node
  5. {
  6. int data;
  7. struct node *l, *r;
  8. };
  9. struct node *creat(int n, char *a, char *b)
  10. {
  11. int i;
  12. struct node *root;
  13. if(n == 0) return NULL;//第二次忘了空节点。。。
  14. root = (struct node *) malloc(sizeof(struct node));//要给root分配空间,第一次忘了。。。
  15. root -> data = b[n-1];
  16. for(i = 0; i < n; i++)
  17. {
  18. if(a[i] == b[n-1])
  19. break;
  20. }
  21. printf("%c", root -> data);
  22. root -> l = creat(i, a, b);
  23. root -> r = creat(n - i - 1, a + i + 1, b + i);
  24. return root;
  25. };
  26. int main()
  27. {
  28. int t;
  29. scanf("%d", &t);
  30. char a[55], b[55];
  31. while(t--)
  32. {
  33. scanf("%s%s", a, b);
  34. int n = strlen(a);
  35. creat(n, a, b);
  36. printf("\n");
  37. }
  38. return 0;
  39. }

先序中序后序知道两个可以求另外一个了,就是有的判断别忘了,感觉有点灵性了。

发表评论

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

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

相关阅读

    相关

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