链接:http://acm.hdu.edu.cn/showproblem.php?pid=1710
题意:给出前序遍历和中序遍历,求出后序遍历
通过前序遍历和中序遍历确定树
前序遍历的第一个数一定是根节点,中序遍历中找到根节点,根节点左侧的均为左子树节点,右侧均为右子树节点
#include <cstdio>
using namespace std;
typedef struct tree {
int num;
tree *l,*r;
}Tree;
Tree *root;
Tree* creat(int *pre,int *in,int n) {
Tree *temp;
for(int i=0;i<n;i++)
if(pre[0]==in[i]) {
temp=new Tree;
temp->num=in[i];
temp->l=creat(pre+1,in,i);
temp->r=creat(pre+i+1,in+i+1,n-(i+1));
return temp;
}
return NULL;
}
void postorder(Tree *rt) {
if(rt==NULL) return;
postorder(rt->l);
postorder(rt->r);
printf(rt==root ? "%d\n" : "%d ",rt->num);
}
int main() {
int n,pre[1005],in[1005];
while(~scanf("%d",&n)) {
for(int i=0;i<n;i++) scanf("%d",&pre[i]);
for(int i=0;i<n;i++) scanf("%d",&in[i]);
root=creat(pre,in,n);
postorder(root);
}
return 0;
}