原题链接:A1020 Tree Traversals
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef struct LevelOrder
{
int data;
int level;
}LevelOrder;
LevelOrder L[35];
int Post[35], In[35], N, cnt = 0;
void getLevelOrder(int l1, int r1, int l2, int r2, int level)
{
if(l1 >= r1 || l2 >= r2) return ;
L[cnt].level = level;
L[cnt++].data = Post[r1-1];
int k = l2;
while(k < r2 && In[k] != Post[r1-1]) k++;
getLevelOrder(l1, l1+k-l2, l2, k, level+1);
getLevelOrder(l1+k-l2, r1-1, k+1, r2, level+1);
}
bool cmp(LevelOrder A, LevelOrder B)
{
return A.level < B.level;
}
int main()
{
scanf("%d", &N);
int i;
for(i=0; i<N; i++) scanf("%d", &Post[i]);
for(i=0; i<N; i++) scanf("%d", &In[i]);
getLevelOrder(0, N, 0, N, 1);
stable_sort(L, L+N, cmp);
printf("%d", L[0].data);
for(i=1; i<N; i++) printf(" %d", L[i].data);
return 0;
}
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstring>
#include <queue>
using namespace std;
typedef struct BiTNode
{
int data;
struct BiTNode *lChild, *rChild;
}BiTNode, *BiTree;
const int MAX = 50;
int Post[MAX], In[MAX];
BiTree buildTree(int inL, int inR, int postL, int postR)
{
if(inL >= inR || postL >= postR) return NULL;
int k = inL;
while(k < inR && In[k] != Post[postR-1]) k++;
BiTree ROOT = new BiTNode;
ROOT->data = Post[postR-1];
ROOT->lChild = buildTree(inL, k, postL, postL+k-inL);
ROOT->rChild = buildTree(k+1, inR, postL+k-inL, postR-1);
return ROOT;
}
void levelOrder(BiTree T)
{
int flag = 0;
queue<BiTree> Q;
Q.push(T);
while(!Q.empty())
{
T = Q.front();
Q.pop();
if(!flag) printf("%d", T->data), flag = 1;
else printf(" %d", T->data);
if(T->lChild) Q.push(T->lChild);
if(T->rChild) Q.push(T->rChild);
}
}
int main()
{
int N;
scanf("%d", &N);
for(int i=0; i<N; i++) scanf("%d", &Post[i]);
for(int i=0; i<N; i++) scanf("%d", &In[i]);
BiTree ROOT = buildTree(0, N, 0, N);
levelOrder(ROOT);
return 0;
}