数据结构试验(用C语言)建立一棵二叉树,并用递归或者非递归的算法分别用先序。中序和后序遍历、谢谢
收起
知与谁同
2018-07-18 09:33:39
2896
0
1
条回答
写回答
取消
提交回答
-
#define LEN sizeof(struct tree)
#define NULL 0
#include<stdio.h>
#include<malloc.h>
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();
}
2019-07-17 22:55:11