二叉树的拷贝、释放

在这里插入图片描述

代码

// ConsoleApplication1.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>



typedef struct BINARYNODE
{
	char ch;
	struct BINARYNODE* left;
	struct BINARYNODE* right;

}BinaryNode;




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

	Recursion(root->left);
	Recursion(root->right);
	printf("%c", root->ch);

}


BinaryNode* CopyTree(BinaryNode* root) //拷贝
{
	if (root == NULL)
		return NULL;

	root->left=CopyTree(root->left);
	root->right=CopyTree(root->right);

	BinaryNode* Node = (BinaryNode*)malloc(sizeof(BinaryNode));
	Node->ch = root->ch;
	Node->left = root->left;
	Node->right = root->right;

	return Node;
}


void FreeTree(BinaryNode* root)//释放
{
	if (root == NULL)
		return;
	FreeTree(root->left);
	FreeTree(root->right);

	free(root);
}

int main(void)
{
	BinaryNode b1, b2, b3, b4, b5, b6, b7, b8;

	b1.ch = 'A'; b1.left = &b2; b1.right = &b3;
	b2.ch = 'B'; b2.left = NULL; b2.right = &b4;
	b3.ch = 'F'; b3.left = NULL; b3.right = &b5;
	b4.ch = 'C'; b4.left = &b6; b4.right = &b7;
	b5.ch = 'G'; b5.left = &b8; b5.right = NULL;
	b6.ch = 'D'; b6.left = NULL; b6.right = NULL;
	b7.ch = 'E'; b7.left = NULL; b7.right = NULL;
	b8.ch = 'H'; b8.left = NULL; b8.right = NULL;

	BinaryNode* root = CopyTree(&b1); //将上面创建的二叉树拷贝给root(根)
	Recursion(root);
	FreeTree(root);

	return 0;
}

结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值