效果
代码实现:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct BindMoniker
{
char ch; //数据域
struct BindMoniker * lChild; //左孩子节点
struct BindMoniker * rChild; //右孩子节点
};
//叶子片数
int calculateLeafNum(struct BindMoniker *root,int *num)
{
if(root ==NULL)
{
return 0;
}
if(root->lChild==NULL ||root->rChild==NULL)
{
(*num)++;
}
calculateLeafNum(root->lChild,num);
calculateLeafNum(root->rChild,num);
}
//统计树的深度
int getTreeHeight(struct BindMoniker *root)
{
if(root==NULL)
{
return 0;
}
//取左子树 和 右子树中最大值 +1
int lnum=getTreeHeight(root->lChild);
int rnum=getTreeHeight(root->rChild);
int num=lnum>rnum?lnum+1:rnum+1;
return num;
}
struct BindMoniker *copyBinaryTree(struct BindMoniker *root)
{
if(root==NULL)
{
return NULL;
}
//拷贝左子树和右子树
struct BindMoniker *lChild =copyBinaryTree(root->lChild);
struct BindMoniker *rChild =copyBinaryTree(root->rChild);
//创建新节点,把我们的俩棵子树连在一起
struct BindMoniker *newnode=(struct BindMoniker *)malloc(sizeof(struct BindMoniker));
newnode->lChild=lChild;
newnode->rChild=rChild;
newnode->ch=root->ch;
//把用户返回给用户
return newnode;
};
//遍历树
void showBinaryTree(struct BindMoniker * root)
{
if (root == NULL)
{
return;
}
printf("%c ", root->ch);
showBinaryTree(root->lChild);
showBinaryTree(root->rChild);
}
void freeTree(struct BindMoniker * root)
{
//释放树
if(root==NULL)
{
return;
}
freeTree(root->lChild);
freeTree(root->rChild);
printf("%c被释放了\n",root->ch);
//释放根节点
free(root);
}
void test01()
{
struct BindMoniker nodeA = { 'A', NULL, NULL };
struct BindMoniker nodeB = { 'B', NULL, NULL };
struct BindMoniker nodeC = { 'C', NULL, NULL };
struct BindMoniker nodeD = { 'D', NULL, NULL };
struct BindMoniker nodeE = { 'E', NULL, NULL };
struct BindMoniker nodeF = { 'F', NULL, NULL };
struct BindMoniker nodeG = { 'G', NULL, NULL };
struct BindMoniker nodeH = { 'H', NULL, NULL };
//建立结点之间的关系
nodeA.lChild = &nodeB;
nodeA.rChild = &nodeF;
nodeB.rChild = &nodeC;
nodeC.lChild = &nodeD;
nodeC.rChild = &nodeE;
nodeF.rChild = &nodeG;
nodeG.lChild = &nodeH;
//1、求树中的叶子的数量
int num = 0;
calculateLeafNum(&nodeA, &num);
printf("叶子的数量为:%d\n", num);
//2、求树的高度/深度
int height = getTreeHeight(&nodeA);
printf("树的高度为: %d\n", height);
//3、拷贝二叉树
struct BindMoniker * newTree = copyBinaryTree(&nodeA);
showBinaryTree(newTree);
printf("\n");
//4、释放二叉树
freeTree(newTree);
}
int main(){
test01();
system("pause");
return 0;
}