作业帮 > 综合 > 作业

数据结构试验(用C语言)建立一棵二叉树,并用递归或者非递归的算法分别用先序.中序和后序遍历、谢谢

来源:学生作业帮 编辑:灵鹊做题网作业帮 分类:综合作业 时间:2024/04/29 10:49:58
数据结构试验(用C语言)建立一棵二叉树,并用递归或者非递归的算法分别用先序.中序和后序遍历、谢谢
能附一点实验思路更好
数据结构试验(用C语言)建立一棵二叉树,并用递归或者非递归的算法分别用先序.中序和后序遍历、谢谢
#define LEN sizeof(struct tree)
#define NULL 0
#include
#include
struct tree
{
char data;
struct tree *lchild,*rchild;
};
//创建二叉树
struct tree *creat()
{
char c;
struct tree *t;
c=getchar();
if(c==' ')
t=NULL;
else
{
t=(struct tree*)malloc(LEN);
t->data=c;
t->lchild=creat();
t->rchild=creat();
}
return t;
}
//前序遍历
void Preprint(struct tree*t)
{
if(t!=NULL)
{
printf("%c->",t->data);
Preprint(t->lchild);
Preprint(t->rchild);
}
}
//中序遍历
void Inprint(struct tree*t)
{
if(t!=NULL)
{
Inprint(t->lchild);
printf("%c->",t->data);
Inprint(t->rchild);
}
}
//后序遍历
void Postprint(struct tree*t)
{
if(t!=NULL)
{
Postprint(t->lchild);
Postprint(t->rchild);
printf("%c->",t->data);
}
}
main()
{
struct tree *t;
printf("Please input tree in order:\n");
t=creat();
printf("The result of Preorder traversal is\n");
Preprint(t);
printf("^\nThe result of Inorder traversal is\n");
Inprint(t);
printf("^\nThe result of Postorder traversal is\n");
Postprint(t);
printf("^\n");
getch();
}