数据结构实验之二叉树四:(先序中序)还原二叉树
Problem Description
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
Input
输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。
Output
输出一个整数,即该二叉树的高度。
Sample Input
9
ABDFGHIEC
FDHGIBEAC
Sample Output
5
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <memory.h>
using namespace std;
typedef struct node tree;
struct node
{
int data;
struct node* left;
struct node* right;
};
tree* create_tree(int n,char a[],char b[])
{
tree* p;
p=(tree*)malloc(sizeof(tree));
p->data=a[0];
if(n==0)
return NULL;
else
{
int i;
for(i=0;i<n;i++)
{
if(a[0]==b[i])
{
break;
}
}
p->left=create_tree(i,a+1,b);
p->right=create_tree(n-1-i,a+1+i,b+1+i);
}
return p;
}
int depth_tree(tree* root)
{
if(!root)
{
return 0;
}
else
{
return max(1+depth_tree(root->left),1+depth_tree(root->right));
}
}
int main()
{
int n;
while(cin>>n)
{
char a[55],b[55];
cin>>a>>b;
tree* root=(tree*)malloc(sizeof(tree));
root = create_tree(n,a,b);
cout<<depth_tree(root)<<endl;
}
return 0;
}