自己对这一块的知识掌握的不是很好,所以就整理了一下,下面是代码;
#include<stdio.h>
#include<malloc.h>
typedef struct tree_node
{
char data;
struct tree_node *lchild,*rchild;
}BT_node;
BT_node *tree;
//树的创建
BT_node *creat_tree(BT_node *tree)
{
char c;
c = getchar();
if(c == '*')
{
tree = NULL;
}
else
{
tree = (struct tree_node *)malloc(sizeof(struct tree_node));
tree->data = c;
tree->lchild = creat_tree(tree->lchild);
tree->rchild = creat_tree(tree->rchild);
}
return(tree);
}
//遍历根节点
void visit_node(BT_node *tree)
{
printf(" ");
putchar(tree->data);
printf("\t");
}
//前序遍历
void pre_tree(BT_node *tree)
{
if(!tree)
{
return;
}
else
{
visit_node(tree);
pre_tree(tree->lchild);
pre_tree(tree->rchild);
}
}
//中序遍历
void mid_tree(BT_node *tree)
{
if(!tree)
{
return;
}
else
{
mid_tree(tree->lchild);
visit_node(tree);
mid_tree(tree->rchild);
}
}
//后序遍历
void after_tree(BT_node *tree)
{
if(!tree)
{
return;
}
else
{
after_tree(tree->lchild);
after_tree(tree->rchild);
visit_node(tree);
}
}
int main()
{
printf("请输入树节点...\n");
tree = creat_tree(tree);
if(tree)
{
printf("前序遍历\n");
pre_tree(tree);
printf("\n");
printf("中序遍历\n");
mid_tree(tree);
printf("\n");
printf("后序遍历\n");
after_tree(tree);
printf("\n");
}
printf("\n");
return 0;
}