题目
思路
用栈模拟树的遍历;
这道题的核心是要明白入队顺序就是先序遍历的顺序;出队顺序为中序遍历的顺序;
理解了这一点,题目就转化为已知先序和中序,输出后序;
单词
implemented:实施,应用;
recursive [rɪˈkɜːsɪv] :递归的,循环的 ;
代码
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <cstring>
#include <string>
#include <math.h>
using namespace std;
const int maxn = 35;
int cnt = 0, n;//后序输出节点的个数
struct node{
int data;
node *left, *right;
};
int pre[maxn], in[maxn];//存储先序和中序
//建树
node* create(int preL, int preR, int inL, int inR){
if(preL > preR) return NULL;
node* root = new node;//返回的根节点
root -> data = pre[preL];
int k = inL;
//在中序中找到根节点,将子树一分为二
while(k <= inR && in[k] != pre[preL]) k ++;
int num = k - inL;
//分别递归构建左子树和右子树
root -> left = create(preL + 1, preL + num, inL, k - 1);
root -> right = create(preL + num + 1, preR, k + 1, inR);
return root;
}
void postOrder(node* root){
if(root == NULL) return;
postOrder(root -> left);
postOrder(root -> right);
printf("%d", root->data);
cnt ++;
if(cnt != n) printf(" ");
return;
}
int main()
{
int preIdx = 0, inIdx = 0;
stack<int> st;//栈
scanf("%d", &n);
string ss;
for(int i = 0; i < 2 * n; i ++){
cin >> ss;
if(ss == "Push"){
scanf("%d", &pre[preIdx++]);
st.push(pre[preIdx - 1]);
}
else{
in[inIdx ++] = st.top();
st.pop();
}
}
node* root = create(0, n - 1, 0, n -1);
postOrder(root);
system("pause");
return 0;
}