http://acm.hdu.edu.cn/showproblem.php?pid=1710
C:不要在for循环内定义变量,在函数开始处定义变量
View Code
#include<stdio.h>
#include<string.h>
#include<malloc.h>
typedef struct tree
{
int data ;
struct tree *l, *r ;
}tree, *tr ;
int flag ;
tr creat(int *root, int*in, int k)
{
tr t ;
int *p ,m;
if(k<=0)
return NULL ;
t = (struct tree*)malloc(sizeof(struct tree)) ;
t->data = *root ;
for(p=in; p!=NULL; p++)
if(*p==*root)
break ;
m = p - in ;
t->l = creat(root+1, in, m) ;
t->r = creat(root+m+1, p+1, k-m-1) ;
return t ;
}
void postorder(tr t)
{
if(t!=NULL)
{
postorder(t->l) ;
postorder(t->r) ;
if(flag)
printf(" ") ;
flag = 1 ;
printf("%d", t->data) ;
}
}
int main()
{
tr t ;
int n,i ;
int root[1001], in[1001] ;
while(scanf("%d", &n)!=EOF)
{
flag = 0 ;
for(i=0; i<n; i++)
scanf("%d", &root[i]) ;
for(i=0; i<n; i++)
scanf("%d", &in[i]) ;
t = creat(root, in, n) ;
postorder(t) ;
puts("") ;
}
return 0 ;
}
C++:
View Code
#include<iostream>
using namespace std;
typedef struct tree
{
int data;
struct tree *r,*l;
}tree,*tr;
int flag;
tr creat(int *a,int *b,int n)
{
tr s;
int *p,k;
if(n <= 0)
return NULL;
s = new tree;
s->data = *a;
for(p=b; p!=NULL; p++)
{
if(*p == *a) break;
}
k = p - b;
s->l = creat(a + 1,b,k);
s->r = creat(a + k + 1,p + 1,n - k - 1);
return s;
}
void postorder(tr b)
{
if(b != NULL)
{
postorder(b->l);
postorder(b->r);
if(flag)
cout<<" ";
flag = 1;
cout<<b->data;
}
}
int main()
{
int a[1001],b[1001];
int n;
while(cin>>n)
{
flag = 0;
for(int i = 0;i < n;i ++)
cin>>a[i];
for(int i = 0;i < n;i ++)
cin>>b[i];
postorder(creat(a,b,n));
cout<<endl;
}
return 0 ;
}
注意输入输出格式,已知先序和中序,求后序
原文链接: https://www.cnblogs.com/yelan/archive/2013/04/01/2994241.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/82912
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!