Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 二叉搜索树的搜索函数出错 struct node*搜索(struct node*root,int x) { 如果(根->键==x | |根==NULL) { 返回根; } 如果(xkey) { 返回搜索(根->左,x); } 其他的 { 返回搜索(根->右,x); } }_C++ - Fatal编程技术网

C++ 二叉搜索树的搜索函数出错 struct node*搜索(struct node*root,int x) { 如果(根->键==x | |根==NULL) { 返回根; } 如果(xkey) { 返回搜索(根->左,x); } 其他的 { 返回搜索(根->右,x); } }

C++ 二叉搜索树的搜索函数出错 struct node*搜索(struct node*root,int x) { 如果(根->键==x | |根==NULL) { 返回根; } 如果(xkey) { 返回搜索(根->左,x); } 其他的 { 返回搜索(根->右,x); } },c++,C++,当我搜索不在二叉搜索树中的元素时,我遇到了分段错误。。怎么了?切换根->键==x和根==NULL以利用|运算符中的短路。您需要检查它是否为null,然后才尝试从中获取属性 现在,在没有子节点的节点上进行搜索时会发生什么?你要么得到search(root->left,x)或搜索(根->右,x),两者都相当于搜索(NULL,x) 此时,第一个if语句变成if(NULL->key==x | | NULL==NULL)NULL->key是对NULL指针的取消引用,这会导致seg故障。非常感谢。。它起作用

当我搜索不在二叉搜索树中的元素时,我遇到了分段错误。。怎么了?

切换
根->键==x
根==NULL
以利用
|
运算符中的短路。您需要检查它是否为null,然后才尝试从中获取属性

现在,在没有子节点的节点上进行
搜索时会发生什么?你要么得到
search(root->left,x)
搜索(根->右,x)
,两者都相当于
搜索(NULL,x)


此时,第一个
if
语句变成
if(NULL->key==x | | NULL==NULL)
NULL->key
是对NULL指针的取消引用,这会导致seg故障。

非常感谢。。它起作用了。。你能详细谈谈你的意见吗。。我没有完全理解它。我知道我们利用了或门的短路特性。。但即使我们不使用它,代码也不会给出seg错误,对吗?@AnuragBharadwaj编辑了我的答案。FIY:在C++中,一个<代码>结构> <代码>(和<代码>类<代码> >定义使得新类型不需要附加的<代码> TyPulf< /C>,并且没有重复<代码> Stutt(不像C,这需要两个之一)。
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);
    }
}