【二叉树的内存管理】创建和释放一棵二叉树

二叉树结点

首先定义一个二叉树结点的结构体

typedef struct MyTreeNode
{
	struct MyTreeNode* left; 
	struct MyTreeNode* right; 
	char data;
}MyTreeNode;

创建一棵二叉树

使用#号法创建一棵二叉树,如果没有左/右子树,则用#号代替,采取先创建根结点、然后创建左子树,最后创建右子树的方法创建二叉树(前序遍历),代码如下:

MyTreeNode * create_tree()
{
	MyTreeNode* node = NULL;
	char c;
	scanf("%c", &c);
	if (c == '#')
	{
		node = NULL;
	}
	else
	{
		node = (MyTreeNode*)malloc(sizeof(MyTreeNode));
		node->data = c;
		node->left = create_tree();
		node->right = create_tree();
	}
	return node;
}

释放一棵二叉树

因为二叉树在创建的时候,所有结点都是malloc分配的,所以需要我们通过free来实现释放二叉树的内存。在释放二叉树的内存时,一定要先释放左右子树,最后释放根结点。代码如下:

void free_tree(MyTreeNode* tree)
{
	if (tree != NULL)
	{
		if (tree->left != NULL)
		{
			free_tree(tree->left);
			tree->left = NULL;
		}
		if (tree->right != NULL)
		{
			free_tree(tree->right);
			tree->right = NULL;
		}
		free(tree);
		tree = NULL;
	}
}

算法测试

首先创建一棵二叉树如下图所示,使用本文的算法创建,并使用前序遍历打印

 测试程序

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

//树结点结构体
typedef struct MyTreeNode
{
	struct MyTreeNode* left; 
	struct MyTreeNode* right; 
	char data;
}MyTreeNode;

//二叉树的前序遍历
void preorder_traversal(MyTreeNode* tree)
{
	if (tree == NULL)
	{
		return;
	}
	printf("%c ", tree->data);
	preorder_traversal(tree->left);
	preorder_traversal(tree->right);
}

//创建一颗二叉树(先创建根,后创建左子树,再创建右子树)
MyTreeNode * create_tree()
{
	MyTreeNode* node = NULL;
	char c;
	scanf("%c", &c);
	if (c == '#')
	{
		node = NULL;
	}
	else
	{
		node = (MyTreeNode*)malloc(sizeof(MyTreeNode));
		node->data = c;
		node->left = create_tree();
		node->right = create_tree();
	}
	return node;
}

//释放一颗二叉树(先释放左右子树,后释放根)
void free_tree(MyTreeNode* tree)
{
	if (tree != NULL)
	{
		if (tree->left != NULL)
		{
			free_tree(tree->left);
			tree->left = NULL;
		}
		if (tree->right != NULL)
		{
			free_tree(tree->right);
			tree->right = NULL;
		}
		free(tree);
		tree = NULL;
	}
}

int main()
{
	MyTreeNode* tree = create_tree();

	printf("前序遍历:");
	preorder_traversal(tree);
	printf("\n");

	free_tree(tree);

	system("pause");
	return 0;
}

运行并输入

ABC#D###EF##G##

 

posted @ 2022-04-09 07:15  Mindtechnist  阅读(55)  评论(0编辑  收藏  举报  来源