数据结构实验之二叉树四:(先序中序)还原二叉树

来源:互联网 发布:数据库人员报表查询 编辑:程序博客网 时间:2024/06/03 14:58

数据结构实验之二叉树四:(先序中序)还原二叉树

Time Limit: 1000MS Memory Limit: 65536KB

Problem Description

给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。

Input

输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。

 

Output

 输出一个整数,即该二叉树的高度。

Example Input

9 ABDFGHIECFDHGIBEAC

Example Output

5

Hint













#include <iostream>

#include <string>

using namespace std;

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

void f(P &t,char preorder[],char inorder[],int length)
{
    if(length!=0)
    {
        t=new Tree;
        t->data=preorder[0];
        int i=0;
        for(;i<length;i++)
        {
            if(inorder[i]==t->data)
            {
                break;
            }
        }
        f(t->left,preorder+1,inorder,i);
        f(t->right,preorder+i+1,inorder+i+1,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 preorder[64],inorder[64];
    int n;
    while(cin>>n)
    {
        cin>>preorder>>inorder;
        f(t,preorder,inorder,n);
        cout<<Deep(t)<<endl;
    }
    return 0;
}