题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805380754817024
注意点
- numLeft = i - inL,一定是减中序的最左
- 29行i - 1写成了inL - 1
- 建树的代码一定要好好看看,特别是递归式
代码
#include<vector>#include<algorithm>#include<iostream>#include<stack>#include<string>using namespace std;const int maxn = 50;struct node{int data;node *lchild;node *rchild;};stack<int> s;int pre[maxn], in[maxn], post[maxn];int num = 0, n;node* create(int preL, int preR, int inL, int inR){if(preL > preR) return NULL;node*root = new node;root->data = pre[preL];//查找下一个根结点int i;for(i = inL; i <= inR; i++){if(in[i] == pre[preL]) break;}int numLeft = i - inL;root->lchild = create(preL + 1, preL + numLeft, inL, inL + numLeft - 1);root->rchild = create(preL + numLeft + 1, preR, i + 1, inR);return root;}void postOrder(node* root){if(root == NULL) return;postOrder(root->lchild);postOrder(root->rchild);printf("%d",root->data);if(num != n - 1) printf(" ");num++;}int main(){scanf("%d",&n);string temps;int tempi, preIndex = 0, inIndex = 0;for(int i = 0; i < n;){cin>>temps;if(temps == "Push"){scanf("%d", &tempi);s.push(tempi);pre[preIndex++] = tempi;}else if(temps == "Pop"){i++;tempi = s.top();s.pop();in[inIndex++] = tempi;}}postOrder(create(0, n - 1, 0, n - 1));return 0;}
