创建一个如下图所示的二叉树
程序如下:
#include<stdio.h>
#include<stdlib.h>
//定义二叉树
typedef struct _tree_node
{
char date;
struct tree_node *lchild;//左节点
struct tree_node *rchild;//右节点
}tree_node;
//创建二叉树
tree_node *create_tree_node(tree_node *new_node)
{
char date = '0';
scanf("%c", &date);
if(date == '0')
{
new_node = NULL;
return new_node;
}
else
{
new_node = (tree_node *)malloc(sizeof(tree_node));
memset(new_node, 0, sizeof(new_node));
new_node->date = date;
new_node->lchild = create_tree_node(new_node->lchild);
new_node->rchild = create_tree_node(new_node->rchild);
return new_node;
}
}
//先序遍历:跟左右
void pre_traver(tree_node *node)
{
if(!node)
{
return;
}
else
{
printf("%c\n", node->date);//跟
pre_traver(node->lchild);//左
pre_traver(node->rchild);//右
}
}
//中序遍历:左跟右
void in_order_traver(tree_node *node)
{
if(!node)
return;
else
{
in_order_traver(node->lchild);//左
printf("%c\n", node->date);//跟
in_order_traver(node->rchild);//右
}
}
//后序遍历:左右跟
void post_order_traver(tree_node *node)
{
if(!node)
return;
else
{
post_order_traver(node->lchild);//左
post_order_traver(node->rchild);//右
printf("%c\n", node->date);//跟
}
}
int main()
{
tree_node *root;
root = create_tree_node(root);
printf("pre_traver\n");
pre_traver(root);
printf("in_order_traver\n");
in_order_traver(root);
printf("post_order_traver\n");
post_order_traver(root);
}
程序运行时按照如下方式输入:
ea0cb00d00f0hg000
程序运行结果如下: