#include <stdio.h>
#include<string.h>
typedef struct tree
{
char data;
struct tree *l,*r;
}tree;
int h;
tree *newtree()
{
tree *t;
t = (tree *)malloc(sizeof(tree));
t -> l = t -> r = NULL;
return t;
}
tree *creat(char front[],char mid[],int n)//建立二叉树
{
if(n == 0) return NULL;
tree *t = newtree();
int i;
t -> data = front[0];
for(i = 0 ; i < n;i++)
{
if(mid[i] == front[0])
break;
}
t -> l = creat(front +1,mid,i);//左子树从第二个开始再次遍历,与中序遍历的二叉树做对比,但只循环到中序根处截至,可知,i即为左子树长度
t -> r = creat(front + i+1,mid+i +1,n-i-1);//经第一遍历,已经确定左子树的长度,又因根仅为一个,所以右子树应该从第二个即左子树的根往后加入有中序遍历计算的左子树长度,而中序树应从第一个往后确定的左子树长度后一个,而遍历长度应该从当前☞最后,但由于循环是由零开始,贵在-1
return t;
}
void get_high(tree *t,int i)
{
if(t)
{
if(h < i)
h = i;
get_high(t -> l,i+1);
get_high(t -> r,i+1);
}
}
int main()
{
tree *t;
char front[55],mid[55];
int n;
while(scanf("%d",&n)!= EOF)
{
t = newtree();
scanf("%s%s",front,mid);
t = creat(front,mid,n);
h = 0;//h需要初始化(why)
get_high(t,1);
printf("%d\n",h);
}
return 0;
}
数据结构实验之二叉树四:(先序中序)还原二叉树
最新推荐文章于 2020-01-10 09:18:46 发布