二叉树
代码:
/*******************************************/
文件名:BT.c
功能:函数内容
/*******************************************/
#ifndef BT_H
#define BT_H
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef char datatype;
typedef struct Node
{
datatype data; //数据域
struct Node *left; //左孩子
struct Node *right; //右孩子
} Node, *BTPtr;
//创建二叉树
BTPtr tree_create();
//先序遍历
void prio_seek(BTPtr B);
//中序遍历
void in_seek(BTPtr B);
//后序遍历
void tail_seek(BTPtr B);
#endif
/*******************************************/
文件名:BT.h
功能:函数声明
/*******************************************/
#include "BT.h"
//创建二叉树
BTPtr tree_create()
{
char data = 0;
scanf(" %c", &data);
if (data == '#')
{
return NULL;
}
BTPtr p = (BTPtr)malloc(sizeof(Node));
if (NULL == p)
{
printf("节点申请失败\n");
return NULL;
}
p->data = data;
p->left = tree_create();
p->right = tree_create();
return p;
}
//先序遍历
void prio_seek(BTPtr B)
{
if (NULL == B)
{
return;
}
printf(" %c\t", B->data);
prio_seek(B->left);
prio_seek(B->right);
}
//中序遍历
void in_seek(BTPtr B)
{
if (NULL == B)
{
return;
}
prio_seek(B->left);
printf(" %c\t", B->data);
prio_seek(B->right);
}
//后序遍历
void tail_seek(BTPtr B)
{
if (NULL == B)
{
return;
}
prio_seek(B->left);
prio_seek(B->right);
printf(" %c\t", B->data);
}
/*******************************************/
文件名:main.c
功能:函数内容
/*******************************************/
#include "BT.h"
int main(int argc, char const *argv[])
{
BTPtr B = tree_create();
if (NULL == B)
{
printf("创建失败\n");
return -1;
}
printf("创建成功\n");
printf("先序遍历结果为:");
prio_seek(B);
printf("\n");
printf("中序遍历结果为:");
in_seek(B);
printf("\n");
printf("后序遍历结果为:");
tail_seek(B);
printf("\n");
return 0;
}