#ifndef _BST_H_
/* Returns negative (left<right), zero (left==right), or positive (left>right). */
typedef int comparator(void* left, void* right);
struct bst_node {
void* data;
struct bst_node* left;
struct bst_node* right;
};
struct bst_node* new_node(void* data);
void free_node(struct bst_node* node);
struct bst_node** search(struct bst_node** root, comparator compare, void* data);
void insert(struct bst_node** root, comparator compare, void* data);
void delete(struct bst_node** node);
#endif
这是一个头文件。
我不了解search
函数,为什么返回类型为node**
?
编辑: 在这里添加了搜索功能:
struct bst_node** search(struct bst_node** root, comparator compare, void* data) {
struct bst_node** node = root;
while (*node != NULL) {
int compare_result = compare(data, (*node)->data);
if (compare_result < 0)
node = &(*node)->left;
else if (compare_result > 0)
node = &(*node)->right;
else
break;
}
return node;
}
答案 0 :(得分:2)
我猜这个函数返回一个指向指针的指针,这样你的search
函数就可以用来实现insert
。如果search
只返回指向节点的指针并且找不到节点,则必须再次遍历树以确定需要重新连接的指针才能进行插入。如果它返回一个指向最终为null的节点指针的指针,那么只需重新指定该指针指向需要插入的新节点即可实现insert
。
只是一个猜测。