Binary Tree Traversals

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 ;
}

注意输入输出格式,已知先序和中序,求后序

 

posted @ 2013-04-01 20:24  yelan@yelan  阅读(188)  评论(0编辑  收藏  举报