讲解的第二道题数据结构上机测试4.1:二叉树的遍历与应用1题目地址
(1)构建结构体
(2)构建二叉树函数以及恢复原二叉树结构的函数
(3 )后序函数
(4)主函数
(1)构建结构体
在二叉树题目中,结构体构建的模板一般是相同的
struct lqc
{
int data;
struct lqc *ltree,*rtree;
};
(2)本题中最重要的就是这个函数的构建;这个函数又可以分为几个小部分
【1】结构体类型函数的定义
【2】判断字符串是否为空
【3】找到根的值!
【4】找到二叉树以根为界分开的左右两部分!
【5】再次使用这个函数,以求出二叉树的左右部分(此处容易出错,应该多加注意!)
【6】返回根的值!
【1】函数的定义
结构体类型函数
struct lqc *create()
()内为三个变量
1:字符串长度len
2:先序结果st1
3:中序结果st2
则如下
struct lqc *create(int len,char st1,char st2)
{
}
【2】此处即为简单的判断语句{为判断长度是否为0}
如果长度为0;返回空(NULL)
如下
if(len==0)
{
return NULL
}
【3】根据题目给出的先序以及中序的结果,很容易找到根的值!
即为先序的第一个!
此处应该先对root开辟空间
root=(struct lqc *)malloc(sizeof(struct lqc));
root->data=st1[0];
【4】
寻找左右两部分也十分容易,根据根的值以及中序结果,则根左边的即为左边部分,根右边即为右边部分!
此处为在中序结果中寻找根的语句。
for(i=0;i<len;i++)
{
if(root->data==st2[i])
{
break;
}
}
【5】
因为如果将左右两部分看做子二叉树的话,左右两部分还需要进行create函数操作!
求root->l以及root->r
root->l=create(i,st1+1,st2);这里的st1+1以及st2代表的是位置
root->r=create(len-i-1,st1+i+1,st2+i+1);
【6】
return root;
(3)后续函数还与原来类似
void houxu(struct lqc *p)
{
if(p!=NULL)
{
houxu(p->ltree);
houxu(p->rtree);
printf("%c",p->data);
}
}
(4)主函数
int main()
{
int len;
char st1[100],st2[100];
struct lqc * root;
scanf("%s %s",st1,st2);
len=strlen(st1);
root=create(len,st1,st2);
houxu(root);
printf("\n");
return 0;
}
完整代码如下
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct lqc
{
char data;
struct lqc *ltree,*rtree;
};
struct lqc *create(int len,char *st1,char *st2)
{
struct lqc *root;
int i;
if(len==0)
{
return NULL;
}
root=(struct lqc *)malloc(sizeof(struct lqc));
root->data=st1[0];
for(i=0; i<len; i++)
{
if(st2[i]==root->data)
{
break;
}
}
root->ltree=create(i,st1+1,st2);
root->rtree=create(len-i-1,st1+1+i,st2+1+i);
return root;
}
void houxu(struct lqc *p)
{
if(p!=NULL)
{
houxu(p->ltree);
houxu(p->rtree);
printf("%c",p->data);
}
}
int main()
{
int len;
struct lqc *root;
char st1[100],st2[100];
gets(st1);
gets(st2);
len=strlen(st1);
root=create(len,st1,st2);
houxu(root);
printf("\n");
return 0;
}
部分代码为参考王子原同学的博客王子原