数据结构实验之二叉树四:还原二叉树

来源:互联网 发布:纸黄金行情软件 编辑:程序博客网 时间:2024/05/05 13:33


数据结构实验之二叉树四:还原二叉树

Time Limit: 1000MS Memory limit: 65536K

题目描述

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

输入

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

输出

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

示例输入

9 ABDFGHIECFDHGIBEAC

示例输出

5

提示


<pre>#include<bits/stdc++.h>using namespace std;struct node{    int data;    struct node *l;    struct node *r;};struct node *creat(char s1[],char s2[],int n){    if(n==0)        return NULL;    struct node *root;    root=new node;    root->data=s1[0];    char *p;    for(p=s2;p!='\0';p++)    {        if(*p==s1[0])        {            break;        }    }    int t=p-s2;    root->l=creat(s1+1,s2,t);    root->r=creat(s1+1+t,p+1,n-t-1);    return root;};int depth(struct node *root){    if(root)    {        int lc=depth(root->l);        int rc=depth(root->r);        if(lc>rc)            return lc+1;        else            return rc+1;    }    else        return 0;}int main(){  int n;  char s1[1000],s2[1000];  while(cin>>n)  {      cin>>s1>>s2;      struct node *root;      root=creat(s1,s2,n);      cout<<depth(root)<<endl;  }  return 0;}



1 0