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

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

  • 相关阅读:
    在过滤器中验证接口中的Token
    导出EXCEL的 两个方法
    调用webservice接口,返回xml(String)转义
    时间类的操作
    jvm 内存解析以及jvm调优
    redis springMVC 配置与应用
    题目2 成绩排序
    题目1 排序
    题目1042:Coincidence
    题目1131:合唱队形
  • 原文地址:https://www.cnblogs.com/yelan/p/2994241.html
Copyright © 2020-2023  润新知