思路
唯一二叉树的建立必须需要中序序列+前序/后序/层次遍历,在题目里面找。这里实在不好看出来。就尝试着把入栈序列出栈序列写出来看看有没有突破口叭。
入栈序列即是前序遍历,出栈序列即是中序遍历
写题历程
代码
#include <iostream>
#include<cstdio>
#include<map>
#include<queue>
#include<string>
#include<algorithm>
#include<vector>
#include<cmath>
#include<stack>
#include<cstring>
using namespace std;
const int maxn = 30;
int n, precnt = 0, incnt = 0, flag = 0;
int pre[maxn+5], in[maxn+5];
stack<int> values;
struct node{
int data;
node* left;
node* right;
};
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;
for(int i = 0; i < n; i++){
if(in[i] == pre[preL]){
k = i;
break;
}
}
int numLeft = k - inL;//左子树节点个数时k - inL而不是k - preL
root->left = create(preL + 1, preL + numLeft, inL, k-1);
root->right = create(preL + 1 + numLeft, preR, k+1, inR);
return root;//没有输出是因为忘记返回rootL !
}
void postTravel(node* root){
//边界条件返回
if(root == NULL) return;
postTravel(root->left);
postTravel(root->right);
if(flag) printf(" ");
flag = 1;
printf("%d", root->data);
}
int main(){
scanf("%d", &n);
getchar();
for(int i = 0; i < 2*n; i++){
char str[5];
scanf("%s", str);
//Push
if(strcmp(str, "Push") == 0){
int numValue;
scanf("%d", &numValue);
values.push(numValue);
pre[precnt++] = numValue;
}else{//pop
in[incnt++] = values.top();
values.pop();
}
}
node* root = create(0, n-1, 0, n-1);
postTravel(root);
return 0;
}