求二叉树的深度

求二叉树的深度

Time Limit: 1000MS Memory limit: 65536K

题目描述

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

输入

输入数据有多组,输入T组数据。每组数据包括两个长度小于<font face="\"Times" new="" roman,="" serif\"="" style="padding: 0px; margin: 0px;">50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。

输出

输出二叉树的深度。

示例输入

2
dbgeafc
dgebfca
lnixu
linux

示例输出

4
3


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef char telemtype;
typedef char status;
typedef struct  bitnode
{
    telemtype data;
    struct bitnode *lchild, *rchild;
}*bitree;

void BinaryTree(bitree& t, char aft[], char ino[],int ps, int is, int length)//ps:后序序列起始位置
//is:中序序列起始位置
{
    if (length==0) t=NULL;
    else
    {
        int k=0;
        int n = strlen(ino);
        for(k=0; k<n; k++)//找到根节点在中序序列中的位置,用以划分左右子树
        {
            if(ino[k]==aft[ps+length-1])//后序序列的最后一个元素即为根节点
                break;
        }
        t= new bitnode;
        if (!t)  exit(0);
        t->data = aft[ps+length-1];
        if (k==is)  t->lchild = NULL;//若仅有一个元素,则此结点左子树为空
        else  BinaryTree(t->lchild, aft, ino, ps, is, k-is);
        if (k==is+length-1)  t->rchild = NULL; //若仅有一个元素,则此结点右子树为空
        else  BinaryTree(t->rchild, aft, ino, ps+(k-is), k+1, length-(k-is)-1);

    }


}
int depth(bitree &t)
{
    int ld, rd;
    if(!t) return 0;
    else
    {
        ld=depth(t->lchild);
        rd=depth(t->rchild);
        if(ld>rd)
            return ld+1;
        else
            return rd+1;
    }

}


int main()
{
    char aft[55], ino[55];
    int m;
    bitree t;
    scanf("%d", &m);
    while(m--)
    {
        scanf("%s", ino);
        scanf("%s", aft);
        int length = strlen(aft);
        BinaryTree(t, aft, ino, 0, 0, length);
        printf("%d\n", depth(t));
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值