二叉树可以使用顺序结构,或者链式结构来 实现这里给出一个链式结构的实现例子
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status; //函数类型的状态
typedef char TElemType;
char EMPTY_NODE = ' ';//空结点
typedef struct Node{
TElemType data;//数据
//左右孩子指针
struct Node *lchild;
struct Node *rchild;
}BiNode,*BiTree;
//构造空二叉树T
Status InitBiTree(BiTree *T){
*T = NULL;
return OK;
}
//判断是否为空树
Status BiTreeEmpty(BiTree T){
if(T){
return FALSE;
} else {
return TRUE;
}
}
//销毁二叉树
void DestroyBiTree(BiTree *T){
if(*T == NULL){
return;
}
//非空进入销毁流程
//采用后续遍历的方式销毁二叉树
DestroyBiTree(&(*T)->lchild);
DestroyBiTree(&(*T)->rchild);
free(*T);
*T = NULL;
}
//使用指定字符串构造空数
//#表示空结点
char *str = "ABDH##K##E##CFI###G#J##";
int strIndex = 0;
void CreateBiTree(BiTree *T)
{
TElemType ch;
//不用判断字符尾,因为不符合接下来的条件的字符将会略过
ch = str[strIndex++];
if(ch == '#'){
*T = NULL;
} else {
*T = (BiNode*)malloc(sizeof(BiNode));
if(!*T){
printf("CreateBiTree malloc fail!\n");
exit(EXIT_FAILURE);
}
//前序遍历生成树
(*T)->data = ch;
CreateBiTree(&(*T)->lchild);
CreateBiTree(&(*T)->rchild);
}
}
int BiTreeDepth(BiTree T){
if(BiTreeEmpty(T)){
return 0;//空树
}
//使用递归解决:当前树的深度等于左右子树中最深的一个+1
int lDepth;
int rDepth;
if(T->lchild){
lDepth = BiTreeDepth(T->lchild)+1;
} else {
lDepth = 1;
}
if(T->rchild){
rDepth = BiTreeDepth(T->rchild)+1;
} else {
rDepth = 1;
}
return lDepth > rDepth ? lDepth : rDepth;
}
TElemType Root(BiTree T){
if(BiTreeEmpty(T)){
return EMPTY_NODE;//空树
} else {
return T->data;
}
}
TElemType Value(BiTree T)
{
return T->data;
}
// 前序遍历
void PreOrderTraverse(BiTree T){
if(T == NULL){
return;
}
printf("%c\n",T->data);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
// 中序遍历
void InOrderTraverse(BiTree T){
if(T == NULL){
return;
}
InOrderTraverse(T->lchild);
printf("%c\n",T->data);
InOrderTraverse(T->rchild);
}
// 后序遍历
void PostOrderTraverse(BiTree T){
if(T == NULL){
return;
}
PostOrderTraverse(T->lchild);
PostOrderTraverse(T->rchild);
printf("%c\n",T->data);
}
int main(){
BiTree tree;
InitBiTree(&tree);
//printf("Empty:%d\n",BiTreeEmpty(tree));
CreateBiTree(&tree);
printf("Empty:%d\n",BiTreeEmpty(tree));
PreOrderTraverse(tree);
printf("Depth:%d\n",BiTreeDepth(tree));
return 0;
}