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

来源:互联网 发布:淘宝微淘在哪 编辑:程序博客网 时间:2024/05/21 08:47

Problem Description

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

Input

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

 

Output

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

Example Input

9 ABDFGHIECFDHGIBEAC

Example Output

5


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char f[101],s[101];
int len;
struct node
{
    char data;
    struct node *l,*r;
}bitnode;
struct node *cre(char f[],char s[],int len)
{
    struct node *t;
    if(!len)
    return NULL;
    int h;
    for(h=0;h<len;h++)
    {
        if(f[0]==s[h])
            break;
    }
    t=(struct node *)malloc(sizeof(struct node ));
    t->data=f[0];
    t->l=cre(f+1,s,h);
    t->r=cre(f+h+1,s+1+h,len-1-h);
    return t;
};
int prin(struct node *t)
{
    int d,j,k;
    if(!t)
        k=0;
    else
    {
        d=prin(t->l);
        j=prin(t->r);
        k=1+(d>j?d:j);
    }
    return k;
}
int main()
{
    int g,k;
    while(~scanf("%d",&g))
    {
            struct node *t;
            scanf("%s%s",f,s);
            t=cre(f,s,g);
            k=prin(t);
            printf("%d\n",k);
    }
    return 0;
}

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