根据后序遍历和中序遍历创建二叉树(代码)

本文介绍了一种使用后序遍历和中序遍历构建二叉树的方法,并通过C语言实现。文章详细展示了如何从给定的后序和中序遍历序列创建二叉树,以及如何进行先序遍历输出。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 100
typedef char ElemType;
//声明二叉树结构体
typedef struct node
{
    ElemType data;
    struct node *lchild,*rchild;
}BitTree;

BitTree *createBinTreeByPostIn(char *post,char *in,int number)
{
    if(number==0) return NULL;
    char c = post[number-1];
    int i = 0;
    while(in[i]!=c && i < number)i++;
    int leftNumber = i;
    int rightNumber = number - i - 1;
    BitTree *node = (BitTree *)malloc(sizeof(BitTree));
    node->data = c;
    node->lchild = createBinTreeByPostIn(&post[0],&in[0],leftNumber);
    node->rchild = createBinTreeByPostIn(&post[leftNumber],&in[i+1],rightNumber);
    return node;
}

void PreOrder(BitTree *bt)
{
    if(bt!=NULL)
    {
        printf("%c ",bt->data);
        PreOrder(bt->lchild);
        PreOrder(bt->rchild);
    }
}
int main(int argc,char **argv)
{
    char a[SIZE],b[SIZE];
    BitTree *p;
    while(scanf("%s%s",a,b)!=EOF)
    {
        p = createBinTreeByPostIn(a,b,strlen(a));
        PreOrder(p);
        printf("\n");
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/wzqstudy/p/10083159.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值