C语言实现二叉树的遍历,拷贝等操作

程序中所用二叉树

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct Binary {
	char ch;
	struct Binary* Lchild;
	struct Binary* Rchild;
};

//计算二叉树的叶子结点数量
void calculuteLeafNum(struct Binary* root, int* pNum) {
	if (root == NULL)
		return;

	if (root->Lchild == NULL && root->Rchild == NULL) {
		(*pNum)++;
	}

	calculuteLeafNum(root->Rchild, pNum);
	calculuteLeafNum(root->Lchild, pNum);
}

//求树的高度/深度
int getTreeHeight(struct Binary* root) {
	if (root == NULL)
		return 0;

	int lHeight = getTreeHeight(root->Lchild);
	int rHeight = getTreeHeight(root->Rchild);

	return lHeight > rHeight ? lHeight + 1 : rHeight + 1;
}

//拷贝二叉树
struct Binary* copyTree(struct Binary* root) {
	if (root == NULL)
		return NULL;
	
	//先拷贝左子树
	struct Binary* lChild = copyTree(root->Lchild);
	//再拷贝右子树
	struct Binary* rChild = copyTree(root->Rchild);

	//在创建一个根节点
	struct Binary* newNode = malloc(sizeof(struct Binary));
	newNode->ch = root->ch;
	newNode->Lchild = lChild;
	newNode->Rchild = rChild;

	return newNode;
}

//树的遍历
void recursion(struct Binary* root) {
	if (root == NULL)
		return;

	printf("%c ", root->ch);
	recursion(root->Lchild);
	recursion(root->Rchild);
}
//二叉树的释放
void freeTree(struct Binary* root) {
	if (root == NULL)
		return;
	freeTree(root->Lchild);
	freeTree(root->Rchild);
	free(root);
}

void test01() {
	struct Binary nodeA = { 'A',NULL,NULL };
	struct Binary nodeB = { 'B',NULL,NULL };
	struct Binary nodeC = { 'C',NULL,NULL };
	struct Binary nodeD = { 'D',NULL,NULL };
	struct Binary nodeE = { 'E',NULL,NULL };
	struct Binary nodeF = { 'F',NULL,NULL };
	struct Binary nodeG = { 'G',NULL,NULL };
	struct Binary 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;

	//计算二叉树的叶子结点数量
	int num = 0;
	calculuteLeafNum(&nodeA, &num);
	printf("二叉树的叶子结点数量为:%d\n", num);

	//求树的高度/深度
	int height = getTreeHeight(&nodeA);
	printf("二叉树的高度为:%d\n", height);

	//树的拷贝
	struct Binary* newTree = copyTree(&nodeA);
	//树的遍历
	recursion(newTree);

	//释放二叉树
	freeTree(newTree);

}


int main()
{
	test01();
	system("pause");
	return EXIT_SUCCESS;
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值