二叉树遍历(已知中序、先序求后序)

灰太狼 2022-06-09 10:38 333阅读 0赞

二叉树的遍历

Time Limit: 1000ms

Memory Limit: 32768KB

This problem will be judged on HRBUST. Original ID: 2040
64-bit integer IO format: %lld Java class name: Main

Prev

Submit Status Statistics Discuss

Next

给出一棵二叉树的中序和前序遍历,输出它的后序遍历。

Input

本题有多组数据,输入处理到文件结束。

每组数据的第一行包括一个整数n,表示这棵二叉树一共有n个节点。

接下来的一行每行包括n个整数,表示这棵树的中序遍历。

接下来的一行每行包括n个整数,表示这棵树的前序遍历。

3<= n <= 100

Output

每组输出包括一行,表示这棵树的后序遍历。

Sample Input

7
4 2 5 1 6 3 7

1 2 4 5 3 6 7

Sample Output

4 5 2 6 7 3 1

Source

2014 Winter Holiday Contest 5

Author

TwIStOy

Prev

Submit Status Statistics Discuss

Next


Distributed under GPLv3. | Project Homepage | Developer: 51isoft crccw | Current Style: Cerulean.

  1. #include<iostream>
  2. #include<cstring>
  3. using namespace std;
  4. int a1[110];
  5. int a2[110];
  6. int n;
  7. int findn(int a)
  8. {
  9. for(int i=0;i<n;i++)
  10. {
  11. if(a2[i]==a) return i;
  12. }
  13. return -1;//要记得return-1
  14. }
  15. void calc(int l1,int r1,int l2,int r2)//返回类型为void
  16. {
  17. int m=findn(a1[l1]);
  18. if(m>l2) calc(l1+1,m-l2+1,l2,m-1);
  19. if(m<r2) calc(m-l2+l1+1,r1,m+1,r2);
  20. cout<<a1[l1]<<" ";
  21. }
  22. int main()
  23. {
  24. // int n;
  25. while(scanf("%d",&n)!=EOF)
  26. {
  27. memset(a1,0,sizeof(a1));
  28. memset(a2,0,sizeof(a2));
  29. for(int i=0;i<n;i++) cin>>a2[i];
  30. for(int i=0;i<n;i++) cin>>a1[i];
  31. calc(0,n-1,0,n-1);
  32. cout<<endl;
  33. }
  34. return 0;
  35. }

发表评论

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

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

相关阅读