2019 PAT甲级秋季考试7-3 Postfix (25 分)

你的名字 2024-04-18 16:03 165阅读 0赞

Given a syntax tree (binary), you are supposed to output the corresponding postfix expression, with parentheses reflecting the precedences of the operators.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 20) which is the total number of nodes in the syntax tree. Then N lines follow, each gives the information of a node (the i-th line corresponds to the i-th node) in the format:

  1. data left_child right_child

where data is a string of no more than 10 characters, left_child and right_child are the indices of this node’s left and right children, respectively. The nodes are indexed from 1 to N. The NULL link is represented by −1. The figures 1 and 2 correspond to the samples 1 and 2, respectively.














infix1.JPG infix2.JPG
Figure 1 Figure 2

Output Specification:

For each case, print in a line the postfix expression, with parentheses reflecting the precedences of the operators.There must be no space between any symbols.

Sample Input 1:

  1. 8
  2. * 8 7
  3. a -1 -1
  4. * 4 1
  5. + 2 5
  6. b -1 -1
  7. d -1 -1
  8. - -1 6
  9. c -1 -1

Sample Output 1:

  1. (((a)(b)+)((c)(-(d))*)*)

Sample Input 2:

  1. 8
  2. 2.35 -1 -1
  3. * 6 1
  4. - -1 4
  5. % 7 8
  6. + 2 3
  7. a -1 -1
  8. str -1 -1
  9. 871 -1 -1

Sample Output 2:

  1. (((a)(2.35)*)(-((str)(871)%))+)
  2. #include<stdio.h>
  3. #include<string.h>
  4. #include<string>
  5. #include<math.h>
  6. #include<iostream>
  7. #include<vector>
  8. #include<algorithm>
  9. using namespace std;
  10. #define INF 0x3f3f3f3f
  11. struct node
  12. {
  13. string val;
  14. int l,r;
  15. }p[5000];
  16. void dfs(int x)
  17. {
  18. if(p[x].l!=-1&&p[x].r!=-1)
  19. {
  20. printf("(");
  21. if(p[x].l!=-1)dfs(p[x].l);
  22. if(p[x].r!=-1)dfs(p[x].r);
  23. cout<<p[x].val;
  24. printf(")");
  25. }
  26. else
  27. {
  28. printf("(");
  29. cout<<p[x].val;
  30. if(p[x].l!=-1)dfs(p[x].l);
  31. if(p[x].r!=-1)dfs(p[x].r);
  32. printf(")");
  33. }
  34. }
  35. int main()
  36. {
  37. int n,i,j,root;
  38. int vis[5000]={0};
  39. scanf("%d",&n);
  40. for(i=1;i<=n;i++)
  41. {
  42. cin>>p[i].val>>p[i].l>>p[i].r;
  43. if(p[i].l!=-1)
  44. vis[p[i].l]=1;
  45. if(p[i].r!=-1)
  46. vis[p[i].r]=1;
  47. }
  48. for(i=1;i<=n;i++)
  49. {
  50. if(vis[i]==0)
  51. {
  52. root=i;
  53. break;
  54. }
  55. }
  56. dfs(root);
  57. }

发表评论

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

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

相关阅读