POJ 2255 Tree Recovery ( 二叉树)

题意:给出一棵二叉树的前序遍历和中序遍历,输出这棵树的后序遍历。

分析:根据前序和中序遍历建树,再后续输出即可,重点在于建树的过程。


//116K  0MS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 30

typedef struct node
{
    char c ;
    node *left , *right ;
}*tree;

char pre[MAX] , in[MAX] ;


int Find_Index ( char c )
{

    int index ;
    index = -1 ;
    int i ;
    for ( i = 0 ; in[i] ; i ++ )
    {
        if ( in[i] == c )
        {
            index = i ;
            break ;
        }
    }
    return index ;
}

tree BuildTree ( int l_pre , int l_in , int len )
{
    tree temp ;
    temp = NULL ;
    if (  len > 0 )
    {
        temp = ( tree ) malloc ( sizeof ( node ) ) ;
        int k ;
        k = Find_Index ( pre[l_pre] ) ;
        temp->c = pre[l_pre] ;
        temp->left = BuildTree(l_pre+1, l_in, k-l_in);
        temp->right = BuildTree(l_pre+1+k-l_in, k+1, len-(k-l_in)-1);
    }
    return temp ;
}

void Print_Tree ( tree t )
{
    if ( t )
    {
        Print_Tree ( t->left ) ;
        Print_Tree ( t->right ) ;
        putchar (t->c) ;
    }
}

int
main ( )
{
    while ( 2 == scanf ("%s%s" , pre , in ) )
    {
        tree T ;
        T = BuildTree ( 0 , 0 , strlen ( pre ) ) ;
        Print_Tree ( T ) ;
        printf ("\n") ;
        free ( T ) ;
    }
    return 0 ;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值