1 Star 0 Fork 0

沈lifeng/script+c_structure

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
l_tree.c 1.83 KB
一键复制 编辑 原始数据 按行查看 历史
moonfish930 提交于 2022-03-30 18:08 . 添加ADT:栈,队列和树
/*
** A binary search tree implemented by linking dynamically allocated
** structures.
*/
#include "tree.h"
#include <assert.h>
#include <stdio.h>
#include <malloc.h>
/*
** The TreeNode structure holds the value and pointers for one
** tree node. 链表实现二叉树
*/
typedef struct TREE_NODE {
TREE_TYPE value;
struct TREE_NODE *left;
struct TREE_NODE *right;
} TreeNode;
/*
** The pointer to the root node in the tree.
*/
static TreeNode *tree;
//不传root参数,会导致tree被修改,所以使用 **link 来指向root
void insert(TREE_TYPE value){
TreeNode *current;
TreeNode **link;
/*
** Start with the root node.
*/
link = &tree;
while((current = *link) != NULL){
if(value < current->value){
link = &current->left;
}else{
assert( value != current->value );
link = &current->right;
}
}
/*
** Allocate a new node; make the proper link field point
** to it.
*/
current = malloc( sizeof( TreeNode ) );
assert( current != NULL );
current->value = value;
current->left = NULL;
current->right = NULL;
*link = current; //重要
}
TREE_TYPE *find( TREE_TYPE value ){
TreeNode *current = tree;
while(current != NULL && current->value != value){
if( value < current->value ){
current = current->left;
}else{
current = current->right;
}
}
if( current != NULL ){
return &current->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 );
}
}
void pre_order_traverse( void (*callback)( TREE_TYPE value ) ){
do_pre_order_traverse(tree, callback);
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/shen-lifeng/script.git
[email protected]:shen-lifeng/script.git
shen-lifeng
script
script+c_structure
master

搜索帮助