//给定先序中序,求后序
//code:
#include <cstdio>
#include <cstring>
#include <stack>
#include <iostream>
using namespace std;
const int MAXN = 35;
struct node{
int data;
node* lChild;
node* rChild;
};
int N;
int preOrder[MAXN], inOrder[MAXN];
node* create(int preL, int preR, int inL, int inR) {
if(preL > preR) return NULL;
node* root = new node;
root->data = preOrder[preL];
int k;
for(k=0; k<N; k++)
if(preOrder[preL] == inOrder[k])
break;
int numLeft = k - inL;
root->lChild = create(preL+1, preL+numLeft, inL, inL+numLeft-1);
//或create(preL+1, preL+numLeft, inL, k-1);
root->rChild = create(preL+numLeft+1, preR, inL+numLeft+1, inR);
//或create(preL+numLeft+1, preR, k+1, inR);
return root;
}
int j = 1;
void dfs(node* root) {
if(root == NULL) return;
dfs(root->lChild);
dfs(root->rChild);
if(j != N){
printf("%d ",root->data);
j++;
} else printf("%d",root->data);
}
int main() {
scanf("%d",&N);
stack<int> s;
char how[5];
int x;
int j_1 = 0, j_2 = 0;
for(int i=0; i<N*2; i++) {
scanf("%s",how);
if(strcmp(how, "Push") == 0) {
scanf("%d",&x);
preOrder[j_1++] = x;
s.push(x);
} else {
inOrder[j_2++] = s.top();
s.pop();
}
}
node* root = create(0, N-1, 0, N-1);
dfs(root);
return 0;
}
1086 Tree Traversals Again (25)
最新推荐文章于 2022-10-08 17:20:05 发布