#include "./03_tree_func.h"
//先序创建
tree* creat_tree()
{
int value = 0;
scanf("%d",&value);
if( -1 == value)
{
return NULL;
}
tree* head = (tree*)malloc(sizeof(tree));
if(NULL == head)
{
printf("节点创建失败\n");
return NULL;
}
head->data = value;
head->lchild = creat_tree();
head->rchild = creat_tree();
return head;
}
//先序遍历
void bianli_pre(tree* head)
{
if(head == NULL)
{
return;//遍历结束标示
}
//先打印跟中的数据
printf("%d ",head->data);
//遍历左子树
bianli_pre(head->lchild);
//遍历右子树
bianli_pre(head->rchild);
return;
}
//中序遍历(左根右)
void mid_bianliTree(tree* head)
{
if(NULL == head)
{
return;
}
//先遍历到最后一个左孩子
mid_bianliTree(head->lchild);
//打印当前根节点的数据
printf("%d ",head->data);
//遍历右子树
mid_bianliTree(head->rchild);
return;
}
//后序遍历
void rear_bianliTree(tree* head)
{
if(NULL == head)
{
return;
}
rear_bianliTree(head->lchild);
rear_bianliTree(head->rchild);
printf("%d ",head->data);
return;
}
#include "./03_tree_func.h"
int main(int argc, const char *argv[])
{
tree* head = creat_tree();
printf("先续遍历\n");
bianli_pre(head);
printf("\n");
printf("中续遍历\n");
mid_bianliTree(head);
printf("\n");
printf("后续遍历\n");
rear_bianliTree(head);
printf("\n");
return 0;
}
#ifndef __TREE_FUNC_H__
#define __TREE_FUNC_H__
#include "stdio.h"
#include <stdlib.h>
#include <string.h>
typedef int dataType;
typedef struct Tree
{
dataType data;
struct Tree* lchild;
struct Tree* rchild;
}tree;
tree* creat_tree();
void bianli_pre(tree* head);
void mid_bianliTree(tree* head);
void rear_bianliTree(tree* head);
#endif