在上篇的基础上,本篇介绍如何进行二叉树的拷贝和释放。从代码中可以看到采用递归方式进行的拷贝、释放操作,基本套路都是一样的。
文章目录
- 1. 二叉树的拷贝
- 2. 二叉树的释放
1. 二叉树的拷贝
#include <iostream>
using namespace std;//定义二叉树节点
class binarynode
{
public:char data; //节点数据域binarynode* lchild; //左孩子binarynode* rchild; //右孩子
};//先序遍历二叉树,对原二叉树和拷贝二叉树进行打印
void Recursion(binarynode* root)
{if (root == nullptr){return;}cout << root->data << endl;//遍历左子树Recursion(root->lchild);//遍历右子树Recursion(root->rchild);
}//拷贝二叉树
binarynode* CopyBinaryTree(binarynode* root)
{if (root == nullptr){return NULL;}//拷贝左子树binarynode* lchild = CopyBinaryTree(root->lchild);//拷贝右子树binarynode* rchild = CopyBinaryTree(root->rchild);//创建节点binarynode* newnode = new binarynode;newnode->data = root->data;newnode->lchild = lchild;newnode->rchild = rchild;return newnode;
}//创建二叉树
void createtree()
{//创建节点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;binarynode* root = CopyBinaryTree(&node1);Recursion(root);}int main()
{createtree();system("pause");return 0;
}
运行结果:
2. 二叉树的释放
#include <iostream>
using namespace std;//定义二叉树节点
class binarynode
{
public:char data; //节点数据域binarynode* lchild; //左孩子binarynode* rchild; //右孩子
};//遍历二叉树,对原二叉树和拷贝二叉树进行打印
void Recursion(binarynode* root)
{if (root == nullptr){return;}cout << root->data << endl;//遍历左子树Recursion(root->lchild);//遍历右子树Recursion(root->rchild);
}//拷贝二叉树
binarynode* CopyBinaryTree(binarynode* root)
{if (root == nullptr){return NULL;}//拷贝左子树binarynode* lchild = CopyBinaryTree(root->lchild);//拷贝右子树binarynode* rchild = CopyBinaryTree(root->rchild);//创建节点binarynode* newnode = new binarynode;newnode->data = root->data;newnode->lchild = lchild;newnode->rchild = rchild;return newnode;
}//释放二叉树内存,进行递归释放
void FreeSpaceBinaryTree(binarynode* root)
{if (root == nullptr){return;}//释放左子树FreeSpaceBinaryTree(root->lchild);//释放右子树FreeSpaceBinaryTree(root->rchild);//释放当前节点delete root;
}//创建二叉树
void createtree()
{//创建节点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;binarynode* root = CopyBinaryTree(&node1);Recursion(root);FreeSpaceBinaryTree(root);}int main()
{createtree();system("pause");return 0;
}
运行结果:
- 二叉树的拷贝和释放