zoukankan      html  css  js  c++  java
  • HDU 1710 二叉树遍历,输入前、中序求后序

    1、HDU  1710  Binary Tree Traversals

    2、链接:http://acm.hust.edu.cn/vjudge/problem/33792  

    3、总结:记录下根结点,再拆分左右子树,一直搜下去。感觉像dfs。

    题意:二叉树,输入前、中序求后序。

    (1)建立出一颗二叉树,更直观。但那些指针用法并不是很懂。

    #include<iostream>
    #include<cstdio>
    #include<cstdlib>
    using namespace std;
    
    typedef struct tree
    {
        tree *l,*r;
        int num;
    };
    tree *root;
    
    tree *build(int *a,int *b,int n)
    {
        tree *s;
        for(int i=0;i<n;i++)
        {
            if(a[0]==b[i]){
                s=(tree *)malloc(sizeof(tree));    //不要漏了这个
    
                s->num=b[i];
                s->l=build(a+1,b,i);
                s->r=build(a+i+1,b+i+1,n-i-1);
                return s;
            }
        }
    
        return NULL;
    }
    
    void postorder(tree *ro)
    {
        if(ro==NULL)return ;
        postorder(ro->l);
        postorder(ro->r);
        if(ro==root){
            printf("%d
    ",ro->num);
        }
        else {
            printf("%d ",ro->num);
        }
    }
    
    int main()
    {
        int n;
        int a[1100],b[1100];
        while(scanf("%d",&n)!=EOF)
        {
            for(int i=0;i<n;i++)
                scanf("%d",&a[i]);
            for(int i=0;i<n;i++)
                scanf("%d",&b[i]);
    
            root=build(a,b,n);
            postorder(root);
        }
    
        return 0;
    }
    View Code

    (2)直接在遍历时输出。

    #include<iostream>
    #include<cstdio>
    using namespace std;
    
    void preorder(int *a,int *b,int n,int flag)
    {
        for(int i=0;i<n;i++)
        {
            if(a[0]==b[i]){
                preorder(a+1,b,i,0);
                preorder(a+i+1,b+i+1,n-i-1,0);
                if(flag){
                    printf("%d
    ",a[0]);
                }
                else {
                    printf("%d ",a[0]);
                }
            }
        }
        return ;
    }
    
    int main()
    {
        int n,a[1100],b[1100];
        while(scanf("%d",&n)!=EOF)
        {
            for(int i=0;i<n;i++)
                scanf("%d",&a[i]);
            for(int i=0;i<n;i++)
                scanf("%d",&b[i]);
    
            preorder(a,b,n,1);
        }
    
        return 0;
    }
    View Code
  • 相关阅读:
    scala的Class
    scala的Map
    log4j配置文件详细解释
    学习线程1之建立线程,并启动
    Spring中WebApplicationContext的研究
    Log4j 配置 的webAppRootKey参数问题
    JNDI绑定数据库
    Struts2配置之Struts.properties
    Java多线程-工具篇-BlockingQueue
    StringUtils判断字符串是否为空的方法
  • 原文地址:https://www.cnblogs.com/sbfhy/p/5785319.html
Copyright © 2011-2022 走看看