介绍:
在静态数组实现二叉搜索树中介绍了数组实现树的具体方法,本文主要介绍用链式的方法实现树。
链式二叉搜索树相比静态数组实现的二叉搜索树最明显的区别在于内存空间的使用率上。静态数组的方式需要分配一整块连续的内存空间,可能会造成内存空间的浪费,而链式的实现方式则有效的利用了内存空间。
函数说明
l_tree.c
- 包含头文件和创建所需的变量
/*
* A binary search tree implemented using a chain structure of dynamic allocation.
*/
#include "tree.h"
#include <assert.h>
#include <stdio.h>
#include <malloc.h>
/*
* The TreeNode structure contains the value and two pointers to a TreeNode.
*/
typedef struct TREE_NODE {
TREE_TYPE value;
struct TREE_NODE *left;
struct TREE_NODE *right;
} TreeNode;
/*
- Pointer to the root node of the tree.
*/
static TreeNode *tree;
创建树节点的类型和指向树根的指针。
- 插入函数
/*
- insert
*/
void insert(TREE_TYPE value)
{
TreeNode *current;
TreeNode **link;
/*
* Start at the root node.
*/
link = &tree;
/*
* Keep looking for values to get into the appropriate subtree.
*/
while ((current = *link) != NULL){
/*
* Entering the left or right subtree, depending on the case (making sure no
* duplicate values occur)
*/
if (value < current->value)
link = ¤t->left;
else {
assert(value != current->value);
link = ¤t->right;
}
}
/*
* Assign a new node with the link field of the appropriate node pointing to it.
*/
current = (TreeNode *)malloc(sizeof(TreeNode));
assert(current != NULL);
current->value = value;
current->left = NULL;
current->right = NULL;
*link = current;
}
找到合适的位置并插入值。current是一个指针变量,它的类型为TreeNode;link也是一个指针变量,但它的类型为TreeNode*。从树根开始遍历各个结点,如果树为空,则通过malloc分配内存空间并使用assert断言判断是否分配成功,成功分配则进行初始化并连接到树中。如果树不为空,则循环遍历整棵树,直到找到一个合适的空位置插入,并查看值是否已存在于树中。循环结束后,link指向要插入的位置,current指向malloc分配的内存空间并初始化后,通过link把结点连接到树中。
- 查找函数
/*
* find
*/
TREE_TYPE *find(TREE_TYPE value)
{
TreeNode *current;
/*
* Start at the root node until you find the value and enter the appropriate subtree.
*/
current = tree;
while (current != NULL && current->value != value){
/*
* Entering the left subtree or the right subtree, depending on the situation.
*/
if (value < current->value)
current = current->left;
else
current = current->right;
}
if (current != NULL)
return ¤t->value;
else
return NULL;
}
如果找到值则返回值在树中的地址,否则返回NULL。
- 前序遍历函数
/*
* do_pre_order_traverse
* Performs a pre-order traversal. This helper function is used to hold information about the
* node we are currently working on.
* This function is not part of the user interface.
*/
static void do_pre_order_traverse(TreeNode *current,
void (*callback)(TREE_TYPE value))
{
if (current != NULL){
callback(current->value);
do_pre_order_traverse(current->left, callback);
do_pre_order_traverse(current->right, callback);
}
}
通过前序遍历遍历树中的结点,把回调函数callback应用于各个结点。
- 把函数指针传递给其他函数进行处理
/*
* pre_order_traverse
*/
void pre_order_traverse(void (*callback)(TREE_TYPE value))
{
do_pre_order_traverse(tree, callback);
}
通过调用前序遍历函数,遍历一次树并将回调函数callback应用于它所遍历过的结点。