数据结构实验之二叉树八:(中序后序)求二叉树的深度
Problem Description
已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。
Input
输入数据有多组,输入T,代表有T组数据。每组数据包括两个长度小于50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。
Output
输出二叉树的深度。
Sample Input
2
dbgeafc
dgebfca
lnixu
linux
Sample Output
4
3
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <memory.h>
using namespace std;
typedef struct node tree;
struct node
{
char 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[n-1];
if(n==0)
return NULL;
else
{
int i;
for(i=0; i<n; i++)
{
if(a[n-1]==b[i])
{
break;
}
}
p->left=create_tree(i,a,b);
p->right=create_tree(n-1-i,a+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()
{
char a[55],b[55];
int n;
cin>>n;
while(n--)
{
cin>>a>>b;
tree* root=(tree*)malloc(sizeof(tree));
root = create_tree(strlen(a),b,a);
cout<<depth_tree(root)<<endl;
}
return 0;
}