前序中序和中序后序还原二叉树

本文介绍了如何通过前序和中序序列,以及中序和后序序列来还原二叉树。在还原过程中,首先确定根节点的位置,然后递归构建左右子树,确保正确重建树的结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前序中序还原二叉树:

struct node *creat(int len,char *str1,char *str2) //由先序序列和中序序列建立二叉树
{
    int i;
    struct node *root;
    if(len==0)
        return NULL;
    root=(struct node*)malloc(sizeof(struct node));
    root->date=str1[0];
    for(i=0;i<len;i++) //找根节点在中序序列的位置
    {
        if(str2[i]==root->date)
            break;
    }
    root->lchild=creat(i,str1+1,str2); //建立左子树
    root->rchild=creat(len-i-1,str1+i+1,str2+i+1); //建立右子树
    return root;
}

中序后序还原二叉树:

struct node *creat(int len,char *str2,char *str1)
{
    int i;
    struct node *root;
    if(len==0)
        return NULL;
    root=(struct node*)malloc(sizeof(struct node));
    root->date=str1[len-1];
    for(i=0;i<len;i++)
    {
        if(str2[i]==root->date)
            break;
    }
    root->lchild=creat(i,str2,str1);
    root->rchild=creat(len-i-1,str2+i+1,str1+i);
    return root;
}

总结:对函数设置3个变量len,str1,str2(len,str2,str1)分别储存序列长度,第一个序列首地址,第二个序列首地址。函数中找到根节点位置用i储存,最后通过递归建立左右子树(注意:函数变量中左右子树的地址为第一个字母的地址!)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值