-
实验目的
Intensify the understanding of tree structure through tree searching, and learn three tree searching algorithms to understanding the principles.
-
实验内容
Using C-language to realize the three of tree searching algorithms, especially using the Double linked list date structure to describe the tree’s structure.
-
使用环境
Win 11 & visual studio code 2022
-
算法介绍
Algorithm: preorder
Procedure preoder (T: ordered rooted tree)
List r
for each offspring c of r from left to right
Tc := subtree with c as root
preorder(T(c))
Algorithm: inorder
Procedure inoder (T: ordered rooted tree)
r := root of T
If r is leaf then List r
Else
l := the first offspring of r from left to right
Tl := subtree with l as root
inorder(T(l))
List r
For each offspring c of r from left to right
Tc := subtree with c as root
inorder(T(c))
Algorithm: postorder
Procedure postoder (T: ordered rooted tree)
r := root of T
For each offspring “c” of r from left to right
postorder(T(c))
List r
-
调试过程
-
调试代码
#include<stdio.h>
#include<stdlib.h>
struct bitnode
{
char Date;//根结点
struct bitnode* Lchild;//左子树
struct bitnode* Rchild;//右子树
};
//创建二叉树
struct bitnode* createtree(struct bitnode* t)
{
char ch;
printf("please input node:");
scanf("%c", &ch);
getchar();
if (ch == '#')
{
t = NULL;
}
else
{
//递归创建结点并赋值
t = (struct bitnode*)malloc(sizeof(struct bitnode));
t->Date = ch;
t->Lchild = createtree(t->Lchild);
t->Rchild = createtree(t->Rchild);
}
return t;
}
void preorder(struct bitnode* t) //先序遍历
{
if (t!= NULL)
{
printf("%c ", t->Date);
preorder(t->Lchild);
preorder(t->Rchild);
}
}
void inorder(struct bitnode* t) //中序遍历
{
if (t != NULL)
{
inorder(t->Lchild);
printf("%c ", t->Date);
inorder(t->Rchild);
}
}
void postorder(struct bitnode* t) //后序遍历
{
if (t != NULL)
{
postorder(t->Lchild);
postorder(t->Rchild);
printf("%c ", t->Date);
}
}
int main()
{
struct bitnode* t=(struct bitnode*)malloc(sizeof(struct bitnode));
t = createtree(t); //创建一个初始二叉树
printf("preorder:");
preorder(t);
printf("\n");
printf("inoder:");
inorder(t);
printf("\n");
printf("postoder:");
postorder(t);
printf("\n");
return 0;
}
-
运行结果
-
总结
Tree is a very useful data structure. Many underlying implementations of database are based on tree structure. Tree search which refers to the repeated access to the nodes of the tree according to certain rules. According to different ways, it can be divided into preorder , inorder, postorder. Because the definition of a tree is recursive, it is not only easy to understand but also simple to use recursive methods to implement the three traversals of a tree.
-
参考文献
[1]谭浩强,C 程序设计[M] (第四版).北京:清华大学出版社,2010年6月(中国高等院校计算机基础教育课程体系规划教材)
[2]谭浩强, C 程序设计( 第四版 )学习辅导 ,北京:清华大学出版社,2010年7月(中国高等院校计算机基础教育课程体系规划教材)
[3]C Primer Plus (第6版)中文版,Stephen Prata 著;姜佑译 ——北京 :人名邮电出版社,2019.11