二叉树的递归遍历->先序,中序,后序,拷贝,释放

本文详细介绍了二叉树的定义与结构,通过C语言实现递归遍历(前序、中序、后序)、复制及释放二叉树的过程。以具体的节点创建实例,演示了如何使用递归进行遍历,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在vs2017可直接运行

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

typedef struct BiNode
{
	char ch;
	struct BiNode *lchild; /* 左孩子 */
	struct BiNode *rchild; /* 右孩子 */
}BNODE;


void recursion(BNODE *root)
{
	if (NULL == root)
		return;
	
	//printf("%c  ", root->ch);		//先序遍历
	
	/* 递归遍历左子树 */
	recursion(root->lchild);
	//printf("%c  ", root->ch);		//中序遍历
	/* 递归遍历右子树 */
	recursion(root->rchild);
	printf("%c  ", root->ch);		//后序遍历
}

/* 递归拷贝二叉树 */
BNODE *copyBinode(BNODE *root)
{
	if (root == NULL)
		return NULL;

	/* 先拷贝左子树 */
	BNODE *newLchild = copyBinode(root->lchild);
	/* 在拷贝右子树 */
	BNODE *newRchild = copyBinode(root->rchild);

	BNODE *newRoot = malloc(sizeof(BNODE));
	newRoot->lchild = newLchild;
	newRoot->rchild = newRchild;
	newRoot->ch = root->ch;

	return newRoot;
}
/* 递归释放拷贝的二叉树 */
void freeSpace(BNODE *root)
{
	if (NULL == root)
		return;

	freeSpace((root)->lchild);
	freeSpace((root)->rchild);

	/* 释放其实是后序遍历*/
	printf("%c被释放\n", root->ch);
	free(root);
}
void test()
{
	BNODE nodeA = { 'A', NULL, NULL };
	BNODE nodeB = { 'B', NULL, NULL };
	BNODE nodeC = { 'C', NULL, NULL };
	BNODE nodeD = { 'D', NULL, NULL };
	BNODE nodeE = { 'E', NULL, NULL };
	BNODE nodeF = { 'F', NULL, NULL };
	BNODE nodeG = { 'G', NULL, NULL };
	BNODE 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;

	printf("后序遍历: ");
	recursion(&nodeA);
	printf("\n*****************************\n");
	BNODE *newroot = copyBinode(&nodeA);
	printf("后序遍历: ");
	recursion(newroot);
	printf("\n*****************************\n");
	freeSpace(newroot);
	newroot = NULL;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值