私は二分木を実装しており、挿入を行い、挿入された値の1つを検索しています。しかし、「Thread 1: EXC_BAD_ACCESS(code=1, address=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 を 1 つ見つけて、それらを出力して、二分探索ツリー関数が検索を実行することをテストしましたが、ご覧のとおり、エラーが発生しています。ただし、コンパイルされます。
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.