首先声明结构体
#pragma once
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<assert.h>
typedef char BTDataType;
typedef struct BinaryTreeNode
{
BTDataType _data;
struct BinaryTreeNode* _left;
struct BinaryTreeNode* _right;
}BTNode;
然后声明一些基本的接口
BTNode* BinaryTreeCreate(BTDataType* a,int *pindex);//创建二叉树
void BinaryTreeDestory(BTNode* root);//销毁二叉树
int BinaryTreeSize(BTNode* root);//计算二叉树的结点个数
int BinaryTreeLeafSize(BTNode* root);//计算二叉树叶子结点的个数
int BinaryTreeLevelkSize(BTNode* root, int k);//计算第k层结点的个数
BTNode* BinaryTreeFind(BTNode* root, BTDataType x);//找到元素为x的结点,并返回该指针
void BinaryTreePreorder(BTNode* root);//先序遍历
void BinaryTreeInorder(BTNode* root);//中序遍历
void BinaryTreePostorder(BTNode* root);//后序遍历
#include"BinaryTree.h"
BTNode* BinaryTreeCreate(BTDataType* a, int *pindex)
{
assert(a);
if (a[*pindex] == '#')
{
++(*pindex);
return NULL;
}
else
{
BTNode* root = (BTNode*)malloc(sizeof(BTNode));
root->_data = a[*pindex];
++(*pindex);
root->_left = BinaryTreeCreate(a, pindex);
root->_right = BinaryTreeCreate(a, pindex);
return root;
}
}
void BinaryTreeDestory(BTNode* root)
{
if (root == NULL)
return;
BinaryTreeDestory(root->_left);
BinaryTreeDestory(root->_right);
free(root);
root = NULL;
}
int BinaryTreeSize(BTNode* root)
{
if (root == NULL)
return 0;
else
{
return 1 + BinaryTreeSize(root->_left) + BinaryTreeSize(root->_right);
}
}
int BinaryTreeLeafSize(BTNode* root)
{
if (root == NULL)
{
return 0;
}
if (root->_left == NULL && root->_right == NULL)
return 1;
return BinaryTreeLeafSize(root->_left) + BinaryTreeLeafSize(root->_right);
}
int BinaryTreeLevelkSize(BTNode* root, int k)
{
if (root == NULL)
{
return 0;
}
if (k == 1)
{
return 1;
}
return BinaryTreeLevelkSize(root->_left, k - 1) + BinaryTreeLevelkSize(root->_right, k - 1);
}
BTNode* BinaryTreeFind(BTNode* root, BTDataType x)
{
if (root == NULL)
return NULL;
if (root->_data == x)
return root;
BTNode* ret;
ret=BinaryTreeFind(root->_left, x);
if (ret)
return ret;
ret = BinaryTreeFind(root->_right, x);
if (ret)
return ret;
return NULL;
}
void BinaryTreePreorder(BTNode* root)
{
if (root == NULL)
return;
printf("%c ", root->_data);
BinaryTreePreorder(root->_left);
BinaryTreePreorder(root->_right);
}
void BinaryTreeInorder(BTNode* root)
{
if (root == NULL)
return;
BinaryTreeInorder(root->_left);
printf("%c ", root->_data);
BinaryTreeInorder(root->_right);
}
void BinaryTreePostorder(BTNode* root)
{
if (root == NULL)
return;
BinaryTreePostorder(root->_left);
BinaryTreePostorder(root->_right);
printf("%c ", root->_data);
}
main函数中测试结果
#include"BinaryTree.h"
int main()
{
char a[] = "ABD##E#H##CF##G##";
int index = 0;
BTNode* tree = BinaryTreeCreate(a,&index);
BinaryTreePreorder(tree);
printf("\n");
BinaryTreeInorder(tree);
printf("\n");
BinaryTreePostorder(tree);
printf("\n");
printf("%d\n", BinaryTreeSize(tree));
printf("%d\n", BinaryTreeLeafSize(tree));
printf("%d\n", BinaryTreeLevelkSize(tree,4));
BinaryTreeDestory(tree);
tree = NULL;
return 0;
}
运行结果如下所示: