二叉搜索树的搜索函数错误

Error in search function of binary search tree

本文关键字:函数 错误 搜索 搜索树      更新时间:2023-10-16
struct node *search(struct node *root, int x)
{
    if(root->key == x || root == NULL)
    {
        return root;
    }   
    if(x < root->key)
    {
        return search(root->left, x);
    }
    else
    {
        return search(root->right, x);
    }
}

当我搜索一个元素不在二叉搜索树时,我得到了一个分割错误。怎么了?

切换root->key == xroot == NULL,以利用||操作符中的短路。您需要检查不是 null,并且只有在尝试从它获取属性时才可以。

现在,当您在没有子节点的节点上获得search时会发生什么?你可以得到search(root->left, x);search(root->right, x);,它们都相当于search(NULL, x);

此时,第一个if语句变为if (NULL->key == x || NULL == NULL)

NULL->key是对空指针的解引用,这会导致segfault