c - 二进制搜索树插入不起作用

标签 c pointers binary-search-tree

我已经研究这个二叉搜索树一段时间了,但我似乎无法插入或更改任何树属性。

我的二叉树定义为:

struct tree{
    Node * root;
    int size;
};
struct node{
    int value;
    Node * left;
    Node * right;
};

因此我的二叉树由节点组成。现在不起作用的部分:

void add(int value, Tree *t){
    //1. if root is null create root
    if(t->root == NULL){
        t->root = nodeCreate(value);
        t->size ++;
        return;
    }
    Node * cursor = t->root;

    while(cursor != NULL){
        if(value == cursor->value){
            printf("value already present in BST\n");
            return;
        }
        if(value < cursor->value){
            cursor = cursor->left;
        }
        if(value > cursor->value){
            cursor = cursor->right;
        }
    }
    //value not found in BST so create a new node.
    cursor = nodeCreate(value);
    t->size = t->size + 1;
}

有人能告诉我哪里错了吗?我预计对 add() 的调用会增加成员的大小并创建新节点,但我似乎无法理解。

最佳答案

我相信以下更改会解决您的问题。

void add(int value, Tree *t){
    if(t->root == NULL){
        t->root = nodeCreate(value);
        t->size ++;
        return;
    }
    Node * cursor = t->root;
    Node * last = null;
    while(cursor != NULL){
        last = cursor;
        if(value == cursor->value){
            printf("value already present in BST\n");
            return;
        }
        if(value < cursor->value){
            cursor = cursor->left;
        }
        if(value > cursor->value){
            cursor = cursor->right;
        }
    }
    //value not found in BST so create a new node.
    cursor = nodeCreate(value);
    if (value > cursor->value)
    {
        last->right = cursor;
    }
    else
    {
        last->left = cursor;
    }
    t->size = t->size + 1;
}

关于c - 二进制搜索树插入不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19595659/

相关文章:

c - 指向指针的指针和指向二维数组的指针之间的区别

c - dbus_g_proxy_call 到 freedesktop "Get"方法给出错误预期类型 gchararray,得到类型代码 'v'

c - 如何确定字符串的长度(不使用 strlen())

c - 仅当我在我的 C 项目中使用代码时出现的 list.h 语法错误

javascript - 二叉搜索树序列化格式

c - 两个 block 的字典顺序比较

C - 用于算术的不兼容指针是否违反严格别名?

c++ - 指向指针数组的指针理解问题

c++ - std::map 可以在迭代器中有效地拆分为两个 std::map 吗?

c - 删除二叉搜索树