用静态数组实现二叉搜索树:
#inclue "tree.h"
#include <assert.h>
#include <stdio.h>
#define TREE_SIZE 100
#define ARRAY_SIZE ( TREE_SIZE + 1 )
/* 用于存储树的所有节点的数组 */
static TREE_TYPE tree[ ARRAY_SIZE ];
/* 计算一个节点左孩子的下标 */
static int left_child( int current )
{
return current * 2;
}
/* 计算一个节点右孩子的下标 */
static int right_child( int current )
{
return current * 2 + 1;
}
/* insert */
void insert( TREE_TYPE value )
{
int current;
/* 确保值为非零,因为零用于提示一个未使用的节点 */
assert( value != 0 );
/* 从根节点开始 */
current = 1;
/* 从合适的字数开始,直到到达一个叶节点 */
while( tree[ current ] != 0 )
{
if( value < tree[ current ] )
current = left_child( current );
else
{
assert( value != tree[ current ] );
current = right_child( current );
}
assert( current < ARRAY_SIZE );
}
tree[ current ] = value;
}
/* find */
TREE_TYPE * find( TREE_TYPE value )
{
int current;
/* 从根节点开始,直到找到那个值,进入合适的子树 */
current = 1;
while( current < ARRAY_SIZE && tree[ current ] != value )
{
if( value < tree[ current ] )
current = left_child( current );
else
current = right_child( current );
}
if( current < ARRAY_SIZE )
return tree + current;
else
return 0;
}
/* 执行一层前序遍历,它并不是用户接口的一部分 */
static void do_pre_order_traverse(
int current, void( *callback )( TREE_TYPE value ) )
{
if(current < ARRAY_SIZE && tree[ current ] != 0 )
{
callback( tree[ current ] );
do_pre_order_traverse( left_child( current ), callback );
do_pre_order_traverse( right_child( current ), callback );
}
}
/* pre_order_traverse */
void pre_order_traverse( void( *callback )( TREE_TYPE value ) )
{
do_pre_order_traverse( 1, callback );
}
用链式实现二叉搜索树:
#include "tree.h"
#include <assert.h>
#include <stdio.h>
#include <malloc.h>
/* TreeNode结构包含了值和两个指向某个树节点的指针 */
typedef struct TREE_NODE
{
TREE_TYPE value;
struct TREE_NODE *left;
struct TREE_NODE *right;
}TreeNode;
/* 指向树根节点的指针 */
static TreeNode *tree;
/* insert */
void insert( TREE_TYPE value )
{
TreeNode *current;
TreeNode **link;
/* 从根节点开始 */
link = &tree;
/* 继续查找值,进入合适的子树 */
while( ( current = *link ) != NULL )
{
if( value < current->value )
link = ¤t->left;
else
{
assert( value != current->value );
link = ¤t->right;
}
}
/* 分配一个新节点,是适应节点的link字段指向它 */
current = malloc( sizeof( TreeNode ) );
assert( current != NULL );
current->value = value;
current->left = NULL;
current->right = NULL;
*link = current;
}
/* find */
TREE_TYPE * find( TREE_TYPE value )
{
TreeNode *current;
/* 从根节点开始 */
current = tree;
while( current != NULL && current->value != value )
{
if( value < current->value )
current = current->left;
else
{
current = current->right;
}
if( current != NULL )
return ¤t->value;
else
return NULL;
}
/* 执行一层前序遍历,这个函数用于保存我们当前正在处理的节点的信息 */
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 );
}
}
/* pre_order_traverse */
void pre_order_traverse( void( *callback )( TREE_TYPE value ) )
{
do_pre_order_traverse( tree, callback );
}