目录
链式二叉树示意图
手搓一个链式二叉树
代码实现
示意图
手搓一个链式二叉树
代码演示:
// 数据类型
typedef int BTDataType;// 二叉树节点的结构
typedef struct BinaryTreeNode
{BTDataType data; //每个节点的数据struct BinaryTreeNode* left; //指向左子树的指针struct BinaryTreeNode* right; //指向右子树的指针
}BTNode;// 申请新节点
BTNode* BuyNode(BTDataType x)
{BTNode* newnode = (BTNode*)malloc(sizeof(BTNode));// 判断是否申请成功if (newnode == NULL){perror("malloc fail");return NULL;}// 初始化newnode->data = x;newnode->left = NULL;newnode->right = NULL;return newnode;
}BTNode* CreatBinaryTree()
{BTNode* n1 = BuyNode(1);assert(n1);BTNode* n2 = BuyNode(2);assert(n2);BTNode* n3 = BuyNode(3);assert(n3);BTNode* n4 = BuyNode(4);assert(n4);BTNode* n5 = BuyNode(5);assert(n5);BTNode* n6 = BuyNode(6);assert(n6);n1->left = n2;n1->right = n4;n2->left = n3;n4->left = n5;n4->right = n6;return n1;
}
代码实现
代码演示:
void BTreeDestory(BTNode* root)
{if (root == NULL)return;BTreeDestory(root->left);BTreeDestory(root->right);free(root);
}
代码解析:
释放链式二叉树的本质是后序遍历
先利用递归找到叶子节点,释放叶子节点,再层层往回返,依次释放即可
代码演示:
释放前:
释放后:
释放后,需要手动将 root 置空
代码如下:
BTNode* root = CreatBinaryTree1();// 释放二叉树
BTreeDestory(root);
root = NULL;