建立一棵二叉树,并对其进行遍历(先序、中序、后序),打印输出遍历结果

来源:百度知道 编辑:UC知道 时间:2024/07/08 01:38:03
[基本要求]
从键盘接受输入(先序),以二叉链表作为存储结构,建立二叉树(以先序来建立),并采用递归算法对其进行遍历(先序、中序、后序),将遍历结果打印输出。
[测试数据]
ABCффDEфGффFффф(其中ф表示空格字符)
则输出结果为 先序:ABCDEGF
中序:CBEGDFA
后序:CGBFDBA
[选作内容]
采用非递归算法实现二叉树遍历。

//只有先序遍历,其它的可以在这个基础上改。
//如果有不懂的可以hi我
#include<stdio.h>
#include<stdlib.h>
typedef struct tnode
{
char data;
struct tnode *lchild;
struct tnode *rchild;

}tnode;
tnode *Tree_creat(tnode *t)
{
char ch;
ch=getchar();
if(ch==' ')
t=NULL;
else
{
if(!(t=(tnode *)malloc(sizeof(tnode))))
printf("Error!");
t->data=ch;//printf("[%c]",t->data);
t->lchild=Tree_creat(t->lchild);
t->rchild=Tree_creat(t->rchild);
}
return t;

}

void preorder(tnode *t)
{
if(t!=NULL)
{
printf("%c ",t->data);

preorder(t->lchild);
preorder(t->rchild);
}

}

void main()
{
tnode *t=NULL;
t=Tree_creat(t);
preorder(t);

}