题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805380754817024

给出先序和中序,求后序序列

注意点

  1. numLeft = i - inL,一定是减中序的最左
  2. 29行i - 1写成了inL - 1
  3. 建树的代码一定要好好看看,特别是递归式

代码

  1. #include<vector>
  2. #include<algorithm>
  3. #include<iostream>
  4. #include<stack>
  5. #include<string>
  6. using namespace std;
  7. const int maxn = 50;
  8. struct node{
  9. int data;
  10. node *lchild;
  11. node *rchild;
  12. };
  13. stack<int> s;
  14. int pre[maxn], in[maxn], post[maxn];
  15. int num = 0, n;
  16. node* create(int preL, int preR, int inL, int inR){
  17. if(preL > preR) return NULL;
  18. node*root = new node;
  19. root->data = pre[preL];
  20. //查找下一个根结点
  21. int i;
  22. for(i = inL; i <= inR; i++){
  23. if(in[i] == pre[preL]) break;
  24. }
  25. int numLeft = i - inL;
  26. root->lchild = create(preL + 1, preL + numLeft, inL, inL + numLeft - 1);
  27. root->rchild = create(preL + numLeft + 1, preR, i + 1, inR);
  28. return root;
  29. }
  30. void postOrder(node* root){
  31. if(root == NULL) return;
  32. postOrder(root->lchild);
  33. postOrder(root->rchild);
  34. printf("%d",root->data);
  35. if(num != n - 1) printf(" ");
  36. num++;
  37. }
  38. int main(){
  39. scanf("%d",&n);
  40. string temps;
  41. int tempi, preIndex = 0, inIndex = 0;
  42. for(int i = 0; i < n;){
  43. cin>>temps;
  44. if(temps == "Push"){
  45. scanf("%d", &tempi);
  46. s.push(tempi);
  47. pre[preIndex++] = tempi;
  48. }else if(temps == "Pop"){
  49. i++;
  50. tempi = s.top();
  51. s.pop();
  52. in[inIndex++] = tempi;
  53. }
  54. }
  55. postOrder(create(0, n - 1, 0, n - 1));
  56. return 0;
  57. }