清华OJ
#include <stdio.h>
#include <stdlib.h>
#define maxSize 4000001
int NumOfNode;
int last;
const int SZ = 1 << 20;
struct fastio
{
char inbuf[SZ];
char outbuf[SZ];
fastio()
{
setvbuf(stdin, inbuf, _IOFBF, SZ);
setvbuf(stdout, outbuf, _IOFBF, SZ);
}
} io;
struct TreeNode
{
TreeNode *leftchild, *rightchild;
int elem;
TreeNode():leftchild(NULL),rightchild(NULL){}
}TreeNodes[maxSize];
int PreOrder[maxSize], PostOrder[maxSize];
template <class T>
inline void scan_d(T &ret) {
char c; ret=0;
while((c=getchar())<'0'||c>'9');
while(c>='0'&&c<='9') ret=ret*10+(c-'0'),c=getchar();
}
int FindLeftRoot(int prefirst, int preend, int postfirst, int postend)
{
for (int i = postfirst; i <= postend; i++)
{
if (PostOrder[i] == PreOrder[prefirst + 1])
{
return i;
}
}
return -1;
}
TreeNode *BuildTree(int prefirst, int preend, int postfirst, int postend)
{
TreeNode *root = new TreeNode();
root->elem = PreOrder[prefirst];
if (postfirst == postend) return root;
int LeftRootId=FindLeftRoot(prefirst,preend,postfirst,postend);
root->leftchild = BuildTree(prefirst + 1, LeftRootId - postfirst + prefirst + 1, postfirst, LeftRootId);
root->rightchild = BuildTree(LeftRootId - postfirst + prefirst + 2, preend, LeftRootId + 1, postend - 1);
return root;
}
void outputByInOrder(TreeNode *tree)
{
if (tree->leftchild != NULL) outputByInOrder(tree->leftchild);
printf("%d ", tree->elem);
if (tree->rightchild != NULL) outputByInOrder(tree->rightchild);
}
int main()
{
last = 0;
scan_d(NumOfNode);
for (int i = 0; i < NumOfNode; i++)
scan_d(PreOrder[i]);
for (int i = 0; i < NumOfNode; i++)
scan_d(PostOrder[i]);
TreeNode *tree = BuildTree(0, NumOfNode - 1, 0, NumOfNode - 1);
outputByInOrder(tree);
return 0;
}