c++ - 在二叉搜索树中搜索对象

标签 c++ data-structures tree segmentation-fault binary-search-tree

**跟踪函数是我用来搜索二叉搜索树的函数,当我在树中搜索某些内容时,它会返回正确的数字顺序,但当我想查看数字是否不存在时,我获取段错误**

  // Binary search tree
  #include <stdio.h>
  #include <iostream>
  #include <assert.h>  
  using namespace std;

struct node
{
int data;
node * left;
node * right;
 };

 node * newNode(int data){
    node * newnode = new node();
 newnode -> data = data;
newnode -> left = NULL;
newnode -> right = NULL;
return newnode;
}


node* Insert (node * root, int data){
if(root == NULL){
root = newNode(data);
}
else if(data <= root-> data){
    root->left = Insert(root->left, data);
}
else{
    root -> right = Insert(root->right, data);
}
return root;
};

int Trace(node* root,int find){
node * searcher = root;
if(searcher->data == find){
    cout << searcher->data << endl;
}
else if(find <= root -> data){
    Trace(searcher->left, find);
    cout << searcher ->data<< endl;
}
else if(find >= root -> data){
    Trace(searcher->right, find);
    cout << searcher ->data << endl;

}
else cout << "not found" << endl;
return searcher-> data;
 };


 int main(){
node * root = NULL;   // creating an empty tree
root = Insert(root, 234234);
root = Insert(root, 2334);
root = Insert(root, 23784);
root = Insert(root, 223);
root = Insert(root, 4244);
root = Insert(root, 673234);
root = Insert(root, 2);
root = Insert(root, 2344);
root = Insert(root, 234);
Trace(root,4244);
return 0;


 }

最佳答案

当您遍历树寻找不存在的成员时,您最终会到达一个 NULL 节点。当您尝试评估其数据时,您会遇到段错误。您可以通过检查您要评估的节点是否有效来避免这种情况。例如,将您的函数 Trace 更改为:

int Trace(node* root, int find) {
    node * searcher = root;
    if(!searcher) {
        cout << "Node not found" << endl;
        //return something here
    }

    //rest of function stays the same
}

关于c++ - 在二叉搜索树中搜索对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37652239/

相关文章:

c# - 为什么C#中的SortedList没有Find方法?

java - 在树状结构中迭代 n 深度

c++ - 数据结构 - 选择排序方法

c++ - 阅读这段代码有问题。如何阅读?

c++ - 使用 opengl 2 从鼠标转换光线

javascript - 在具有任意数量子 Node 的树中,查找 Node 是否在给定 Node 的左半子树或右半子树中

c++ - MFC 功能区主页按钮双击关闭应用程序

algorithm - 通过仅以相同顺序插入节点来从 Preorder 获得 BST

java - Java中如何存储树结构?

c++ - 使用 C++ 在二叉搜索树中存储值