由先序和中序还原二叉树

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char ElemType;
typedef struct BiTNode
{
    ElemType data;
    struct BiTNode *lchild;
    struct BiTNode *rchild;
} BiTNode,*BiTree;

int Search(char pre[],char ch)
{
    int a = strlen(pre);
    int i;
    for(i = 0; i <= a - 1; i++)
    {
        if(pre[i] == ch)
            return i;
    }
    return -1;
}
BiTree Create(char pre[],char ino[],int ps,int is,int n)
{
    BiTree T;
    if(n == 0)
        T = NULL;
    else
    {
        int k;
        k = Search(ino,pre[ps]);
        if(k == -1)
        {
            T = NULL;
        }
        else
        {
            T = (BiTNode *)malloc(sizeof(BiTNode));
            if(!T) return 0;
            T->data = pre[ps];
            if(k == is)//左子树为空
                T->lchild = NULL;
            else
            {
                T->lchild = Create(pre,ino,ps + 1,is,k - is);
            }
            if(n == k - is + 1)
            {
                T->rchild =NULL;
            }
            else
            {
                T->rchild = Create(pre,ino,ps + 1 + k - is,k + 1,n - 1 - (k - is));
            }
        }
    }
    return T;
}
int Depth(BiTree T)
{
    int depth;
    if(!T)
        depth = 0;
    else
    {
        int m,n;
        m = Depth(T->lchild);
        n = Depth(T->rchild);
        depth = (m > n ? m : n) + 1;
    }
    return depth;
}
int main()
{
    int n;
    BiTree T;
    while(~scanf("%d",&n))
    {
        char pre[100],ino[100];
        scanf("%s",pre);
        scanf("%s",ino);
        T = NULL;
        T = Create(pre,ino,0,0,n);
        int x;
        x = Depth(T);
        printf("%d\n",x);
    }

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值