我有一个二进制搜索树,我试图实现插入功能。然而,当我测试代码时,我发现没有任何元素会被添加,尽管我的逻辑看起来很好。我觉得我缺少一些C特质。二元搜索树不添加元素
struct tree_element {
int data;
struct tree_element* left;
struct tree_element* right;
};
typedef struct tree_element node;
void init(node* root){
root->left = NULL;
root->right = NULL;
root->data = 0;
}
void insert(node* root, int val){
if (root == NULL){
root = (node*)(malloc(sizeof(node)));
init(root);
root->data = val;
printf("added %i\n", val);
return;
}
if (val > root->data){
insert(root->right, val);
}
else {
insert(root->left, val);
}
}
您需要使用双指针(指向指针的指针),但实际上更容易将结点作为“insert”中的函数结果返回。 –
为什么需要双指针?当前的代码是如何防止添加节点? –
[许多*重复此问题之一](https://stackoverflow.com/questions/6349196/binary-search-tree-pointer-problem)。 – WhozCraig