简体   繁体   中英

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)

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. 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. 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 . This value then get dereferenced because you don't check if you found the value but assume that it is there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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