求二叉树的深度

题目描述
已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。

输入
输入数据有多组,输入T,代表有T组数据。每组数据包括两个长度小于50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。

输出
输出二叉树的深度。
示例输入
2
dbgeafc
dgebfca
lnixu
linux
示例输出
4

3

#include<stdio.h>
#include<malloc.h>
#include<string.h>
char zx[51],hx[51];
int vis[51],maxn;
struct node
{
    int data;
    struct node *left,*right;
};
typedef node *tree;
tree build(int s,int e)
{
    if(s>e) return NULL;
    int i,ans=0,pos=0;
    for(i=s;i<=e;i++)
    {
        if(vis[zx[i]-'a']>ans)
        {
            ans=vis[zx[i]-'a'];
            pos=i;
        }
    }
    tree root=(tree)malloc(sizeof(node));
    root->data=zx[pos];
    root->left=build(s,pos-1);
    root->right=build(pos+1,e);
    return root;
}
void bl(tree root,int f)
{

    if(root==NULL) return;
    if(maxn<f)
            maxn=f;
        bl(root->left,f+1);
        bl(root->right,f+1);
}
void del(tree root)
{
    if(root->left) del(root->left);
    if(root->right) del(root->right);
    free(root);
}
int main()
{
    freopen("b.txt","r",stdin);
    int n;
    while(scanf("%d",&n)==1)
    {
        while(n--)
        {
            memset(vis,0,sizeof(vis));
            scanf("%s",zx);
            scanf("%s",hx);
            int len=strlen(zx),i;
            for(i=0;i<len;i++)
                vis[hx[i]-'a']=i;
            tree root=build(0,len-1);
            maxn=0;
            bl(root,1);
            del(root);
            printf("%d\n",maxn);
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值