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

来源:互联网 发布:珠宝标签打印软件 编辑:程序博客网 时间:2024/06/05 22:44

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

Time Limit: 1000MSMemory Limit: 65536KB
SubmitStatistic Discuss

Problem Description

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

Input

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

 

Output

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

Example Input

9 ABDFGHIECFDHGIBEAC

Example Output

5

Hint

#include<cstdio>#include<cstring>#include<cstdlib>using namespace std;typedef struct node{    char data;    struct node *l;    struct node *r;}BTnode;char pre[55],in[55];BTnode *Create(char pre[],char in[],int n){    BTnode *root;    char *p;    int k;    if(n<=0) return NULL;    root=(BTnode *)malloc(sizeof(BTnode));    root->data=*pre;    for(p=in;p<in+n;p++)        if(*p==*pre)        break;    k=p-in;    root->l=Create(pre+1,in,k);    root->r=Create(pre+k+1,p+1,n-k-1);    return root;}int Gethigh(BTnode *root){    int n,m;    if(root==NULL)        return 0;    else    {        n=Gethigh(root->l);        m=Gethigh(root->r);        if(n>m)            return n+1;        else            return m+1;    }}int main(){    int n;    while(scanf("%d",&n)!=EOF)    {        scanf("%s",pre);        scanf("%s",in);        BTnode *root;        root=Create(pre,in,n);        printf("%d\n",Gethigh(root));    }    return 0;}


阅读全文
0 0