二叉树的编程

效果在这里插入图片描述

代码实现:

#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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值