[英]C++ Binary Search Tree error
我正在實現一個二叉樹,並進行一些插入並搜索插入的值之一。 但是我收到內存錯誤,提示“線程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並打印出來以測試二進制搜索樹函數是否可以執行搜索工作,但是如您所見,我遇到了錯誤。 它雖然編譯。
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.
您的insertion()
代碼錯誤。 您可能打算使用
if (root == nullptr) { ... }
照原樣,您的樹將僅包含一個節點! 然后,當您搜索值時,它將找不到該值並返回nullptr
。 然后,該值將被取消引用,因為您無需檢查是否找到了該值,而是認為它在那里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.