简体   繁体   English

C ++二进制搜索树错误

[英]C++ Binary Search Tree error

I am implementing a binary tree and do some insertion and search one of the inserted values. 我正在实现一个二叉树,并进行一些插入并搜索插入的值之一。 But I am getting memory error saying "Thread 1: EXC_BAD_ACCESS(code=1, address=0x0) 但是我收到内存错误,提示“线程1:EXC_BAD_ACCESS(code = 1,address = 0x0)

my binary tree is like the following 我的二叉树如下

  struct node
  {
        int data;
        node* left = nullptr;
        node* right = nullptr;

        explicit node(int data) : data(data) {};
  };

my insertion function is like the following 我的插入函数如下

  node* insertion(node* root, int value)
  {
        if (root != nullptr) return new node(value);

        if (value < root->data)
        {
              root->left = insertion(root->left, value);
        }
        else
        {
              root->right = insertion(root->right, value);
        }

        return root;
  }

My Binary Search function is like the following 我的二进制搜索功能如下

  node* binary_search(node* root, int value)
  {
        if (root == nullptr || root->data == value)
        {
              return root;
        }

        if (value < root->data) return binary_search(root->left, value);
        else return binary_search(root->right, value);
  }

so in main function, I inserted several values to root and try to find one value 13 and print them out to test binary search tree function does its job to search, but as you see I am getting errors. 因此,在主函数中,我在根目录中插入了多个值,并尝试找到一个值13并打印出来以测试二进制搜索树函数是否可以执行搜索工作,但是如您所见,我遇到了错误。 It compiles though. 它虽然编译。

  struct node* root = new node(NULL);
  root->data = 10;
  root = insertion(root, 1);
  root = insertion(root, 11);
  root = insertion(root, 2);
  root = insertion(root, 12);
  root = insertion(root, 3);
  root = insertion(root, 13);
  root = insertion(root, 5);
  root = insertion(root, 20);
  root = insertion(root, 7);
  root = insertion(root, 15);

  auto temp1 = binary_search(root, 13);
  cout << "Did you find 13? : " << temp1->data << endl; 
   // Here I am getting that error.

Your insertion() code is wrong. 您的insertion()代码错误。 You probably meant to use 您可能打算使用

if (root == nullptr) { ... }

As is, your tree will contain just one node! 照原样,您的树将仅包含一个节点! When you then search for your values, it doesn't find the value and returns nullptr . 然后,当您搜索值时,它将找不到该值并返回nullptr This value then get dereferenced because you don't check if you found the value but assume that it is there. 然后,该值将被取消引用,因为您无需检查是否找到了该值,而是认为它在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM