码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1710 二叉树遍历,输入前、中序求后序

时间:2016-08-18 21:26:06      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

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\n",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\n",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

 

HDU 1710 二叉树遍历,输入前、中序求后序

标签:

原文地址:http://www.cnblogs.com/sbfhy/p/5785319.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!