二叉树从先序遍历和中序遍历得出后序遍历

由树的先序遍历序列和中序遍历序列创建一棵二叉树。

输出二叉树的后序遍历序列。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char ElementType;
typedef struct BiTNode {
    ElementType data;
    struct BiTNode* lchild;
    struct BiTNode* rchild;
}BiTNode, * BiTree;
BiTree CreatBinTree(char* pre, char* in, int n)
{
    BiTree T;
    int i;
    if (n <= 0) return NULL;
    T = (BiTree)malloc(sizeof(BiTNode));
    T->data = pre[0];
    for (i = 0; in[i] != pre[0]; i++);
    //找到中序遍历中与先序遍历中第一个相同元素的位置
    //中序中前i个是左子树,后i个是右子树
    T->lchild = CreatBinTree(pre + 1, in, i);
    //建立右子树,后i个是右子树,所以中序的后i个是右子树,先序的后i个是右子树
    T->rchild = CreatBinTree(pre + i + 1, in + i + 1, n - i - 1);
    return T;
}
void  pr(BiTree T)
{
    if (T)
    {
        pr(T->lchild);
        pr(T->rchild);
        printf("%c", T->data);
    }
}
int main()
{
    BiTree T;
    char prelist[100];
    char inlist[100];
    int length;
    printf("请输入前序遍历:"); 
    scanf("%s", prelist);
    printf("请输入中序遍历:"); 
    scanf("%s", inlist);
    length = strlen(prelist);
    T = CreatBinTree(prelist, inlist, length);
    printf("后序遍历的结果是:");
    pr(T);
    return 0;
}

测试数据:

先序遍历序列:ABDGCEF

中序遍历序列:DGBAECF

514797b7df7c47baa044a658f9c8de5b.png

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值