二进制搜索树未添加元素

奎因·麦克休

我有一个二叉搜索树,我正在尝试为其执行插入功能。但是,当我测试代码时,我发现根本没有添加任何元素,即使我的逻辑对我来说也不错。我觉得我缺少一些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);
    }
}
安德鲁·谢泼德

root可以在函数中更改值。但是,从调用函数的角度来看,什么都没有改变。

这可能起作用:

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);
    }
}

基本概念是-当您将指针传递给方法时,该方法可以更改指针所指向的数据,但不能更改指针本身。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章