我正在实现一棵二叉树并进行一些插入并搜索其中一个插入的值。但我收到内存错误消息“线程 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.