0

我正在实现一棵二叉树并进行一些插入并搜索其中一个插入的值。但我收到内存错误消息“线程 1:EXC_BAD_ACCESS(代码=1,地址=0x0)

我的二叉树如下

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

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

我的插入功能如下

  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;
  }

我的二分搜索功能如下

  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);
  }

所以在主函数中,我向根插入了几个值并尝试找到一个值 13 并将它们打印出来以测试二叉搜索树函数是否可以进行搜索,但正如您所见,我遇到了错误。它虽然编译。

  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.
4

1 回答 1

1

你的insertion()代码是错误的。您可能打算使用

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

照原样,您的树将只包含一个节点!然后,当您搜索您的值时,它找不到该值并返回nullptr。然后这个值会被取消引用,因为您不检查是否找到了该值,而是假设它在那里。

于 2013-08-24T00:09:02.237 回答