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.