#include<iostream>
#include <malloc.h>
using namespace std;
struct node
{
char data;
struct node *rchild,*lchild;
}tree;
struct node *creat(char *a1,char*a2,int n)
{
struct node *root;
if(n<=0) return NULL;
else
{
root=(struct node *)malloc(sizeof(struct node ));
root->data=*a1;//*a1亦可写作a1[0];
//将先序遍历的第一个节点当作当前子树的根
/*
char *a;
for (a=a2;a!=NULL;a++)
{
if(*a==*a1)//*a1亦可写作a1[0]
break;
}
int lchildroot=a-a2;//左子树的长度
root->lchild=creat(a1+1,a2,lchildroot);
root->rchild=creat(a1+1+lchildroot,a+1,n-lchildroot-1);
*/
int i;
for ( i=0;i<n;i++)
{
if(a2[i]==*a1)//*a1亦可写作a1[0]
break;
}
int lchildroot=i;//左子树的长度
root->lchild=creat(a1+1,a2,lchildroot);
root->rchild=creat(a1+1+lchildroot,a2+1+lchildroot,n-lchildroot-1);
}
return root;
};
int deep(struct node *root)
{
int d=0;
if(root)
{
int l=deep(root->lchild);
int r=deep(root->rchild);
d=l>r?l+1:r+1;
}
return d;
}
int main()
{
int n;
while(cin>>n)
{
char a1[55],a2[55];
struct node *root;
cin>>a1>>a2;
root=creat(a1,a2,n);
cout<<deep(root)<<endl;
}
}
3343 数据结构实验之二叉树四:(先序中序)还原二叉树
最新推荐文章于 2022-07-12 14:35:31 发布