二叉树的基本操作

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>


//二叉树结点
typedef struct BINARYNODE {
	char ch;
	struct BINARYNODE* lchild;
	struct BINARYNODE* rchild;
}BinaryNode;

//拷贝二叉树
BinaryNode* CopyBinaryTree(BinaryNode* root) {
	if (root == NULL) return NULL;

	BinaryNode* lchild = CopyBinaryTree(root->lchild);
	BinaryNode* rchild = CopyBinaryTree(root->rchild);

	//创建节点
	BinaryNode* newnode = (BinaryNode*)malloc(sizeof(BinaryNode));
	newnode->ch = root->ch;
	newnode->lchild = lchild;
	newnode->rchild = rchild;

	return newnode;
}

//释放内存
void FreeSpaceBinary(BinaryNode* root) {
	if (root == NULL) return;
	FreeSpaceBinary(root->lchild);
	FreeSpaceBinary(root->rchild);
	free(root);
}

//求二叉树的高度
int CaculateTreeDepth(BinaryNode* root) {
	if (root == NULL) {
		return 0;
	}
	int depth = 0;
	int leftDepth = CaculateTreeDepth(root->lchild);
	int rightDepth = CaculateTreeDepth(root->rchild);
	depth = leftDepth > rightDepth ? leftDepth + 1: rightDepth + 1;
	return depth;
}

void CaculateLeafNum(BinaryNode* root,int* leafNum) {
	if (root == NULL) return;
	if (root->rchild == NULL && root->lchild == NULL) {
		(*leafNum)++;
	}
	CaculateLeafNum(root->lchild, leafNum);
	CaculateLeafNum(root->rchild, leafNum);
}

//递归遍历
void Recursion(BinaryNode* root)
{
	if (root == NULL)
		return;

	//先序遍历
	//printf("%c", root->ch);
	//Recursion(root->lchild);
	//Recursion(root->rchild);


	中序遍历
	//Recursion(root->lchild);
	//printf("%c", root->ch);
	//Recursion(root->rchild);

	//后序遍历
	Recursion(root->lchild);
	Recursion(root->rchild);
	printf("%c", root->ch);



}


void CresteBinaryTree() {
	//创建节点
	BinaryNode node1 = { 'A',NULL,NULL };
	BinaryNode node2 = { 'B',NULL,NULL };
	BinaryNode node3 = { 'C',NULL,NULL };
	BinaryNode node4 = { 'D',NULL,NULL };
	BinaryNode node5 = { 'E',NULL,NULL };
	BinaryNode node6 = { 'F',NULL,NULL };
	BinaryNode node7 = { 'G',NULL,NULL };
	BinaryNode node8 = { 'H',NULL,NULL };

	//建立节点关系
	node1.lchild = &node2;
	node1.rchild = &node6;
	node2.rchild = &node3;
	node3.lchild = &node4;
	node3.rchild = &node5;
	node6.rchild = &node7;
	node7.lchild = &node8;


	//遍历
	Recursion(&node1);
	printf("\n");
	
	//叶子节点数
	int leafNum = 0;
	CaculateLeafNum(&node1,&leafNum);
	printf("叶子节点的数目:%d\n", leafNum);

	std::cout << CaculateTreeDepth(&node1)<<std::endl;

	BinaryNode* root = CopyBinaryTree(&node1);
	Recursion(root);

}

int main() {
	CresteBinaryTree();
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值