1 '二叉树01-结点类
创建“二叉树”工程项目,在该项目中创建结点类头文件 TNode.h。在该头文件中声明二叉树的结点类型。
TNode.h
#ifndef _TNode_h_
#define _TNode_h_
// 定义二叉树结点类型
typedef struct _TNODE_
{
// 数据域
char data;
// 指针域(左、右孩子指针)
struct _TNODE_ *lch, *rch;
} TNODE;
#endif
2-创建二叉树
// 创建二叉树
void BinTreeCreate(TNODE **root);
说明:root 为指向二叉树根指针的指针。
在工程项目中创建二叉树头文件 BinTree.h 和 BinTree.c。
在头文件 BinTree.h 中声明函数,在程序文件 BinTree.c 中编写函数
BinTree.h
#ifndef _BinTree_h_
#define _BinTree_h_
#include "TNode.h"
// 创建二叉树
void BinTreeCreate(TNODE **root);
#endif
BinTree.c
#include <stdio.h>
#include <stdlib.h>
#include "BinTree.h"
void BinTreeCreate(TNODE **root)
{
*root = NULL;
}
3-清空二叉树
void BinTreeClear(TNODE **root);
{
if(*root)
{
BinTreeClear(&(*root)->lch);
BinTreeClear(&(*root)->rch);
free(*root);
*root = NULL;
}
}
4-销毁二叉树
void BinTreeDestroy(TNODE **root)
{
BinTreeClear(&(*root));
free(*root);
}
5.输入二叉树
函数原型
// 输入二叉树
void BinTreeInput(TNODE **root);
// 输入二叉树(内部递归)
static void BinTreeInput1(TNODE **root);
说明:root为指向二叉树或子树的根指针的指针。
BinTreeInput 函数是供外部用户使用的函数。
BinTreeInput1 函数是供内部使用的递归函数。
提示:
BinTreeInput 在输入之前应先调用 BinTreeClear 清空二叉树以确保不发生内存泄漏,然后再调用 BinTreeInput1 输入二叉树。
BinTreeInput1 输入二叉树时按先根遍历顺序输入结点的值,用特殊字符 ‘#’ 来表示空树。
在头文件 BinTree.h 添加函数声明。
static void BinTreeInput1(TNODE **root)
{
char x;
scanf(" %c", &x);
if('#' == x)
{
*root = NULL;
}
else
{
*root = (TNODE*)malloc(sizeof(TNODE));
(*root)->data = x;
BinTreeInput1(&(*root)->lch);
BinTreeInput1(&(*root)->rch);
}
}
void BinTreeInput(TNODE **root)
{
BinTreeclear(root);
BinTreeInput1(root);
}
6-先序遍历
void BinTreePreorder(const TNODE *root)
{
if(root)
{
putchar(root->data);
BinTreePreorder(root->lch);
BinTreePreorder(root->rch);
}
}
7-中序遍历
void BinTreeInorder(const TNODE *root)
{
if(root)
{
BinTreeInorder(root->lch