数据结构实验之二叉树四:(先序中序)还原二叉树

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值