数据结构实验之二叉树八:(中序后序)求二叉树的深度

来源:互联网 发布:淘宝网怎么装修店铺 编辑:程序博客网 时间:2024/06/07 05:54

数据结构实验之二叉树八:(中序后序)求二叉树的深度

Time Limit: 1000MS Memory Limit: 65536KB

Problem Description

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

Input

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

Output

输出二叉树的深度。

Example Input

2dbgeafcdgebfcalnixulinux

Example Output

43



#include <iostream>
#include <string.h>

using namespace std;

typedef struct Tree
{
    char data;
    struct Tree *left,*right;
}*P;

void f(P &t,char inorder[],char pastorder[],int length)
{
    if(length!=0)
    {
        t=new Tree;
        t->data=pastorder[length-1];
        int i=0;
        for(;i<length;i++)
        {
            if(inorder[i]==t->data)
            {
                break;
            }
        }
        f(t->left,inorder,pastorder,i);
        f(t->right,inorder+i+1,pastorder+i,length-i-1);
    }
    else
    {
        t=NULL;
    }
}

int Deep(P &t)
{
    int n=0;
    if(t)
    {
        int n1=Deep(t->left);
        int n2=Deep(t->right);
        if(n1>n2)
        {
            n=n1+1;
        }
        else
        {
            n=n2+1;
        }
    }
    return n;
}

int main()
{
    P t;
    char pastorder[64],inorder[64];
    int n;
    cin>>n;
    while(n--)
    {
        cin>>inorder>>pastorder;
        f(t,inorder,pastorder,strlen(pastorder));
        cout<<Deep(t)<<endl;
    }
    return 0;
}








阅读全文
0 0
原创粉丝点击