[英]Binary tree code below is giving segmentation fault. Can anyone explain why?
我正在嘗試編寫二進制樹。 首先,我檢查根是否為空,如果是,則將數據分配給根。 但是代碼給分段錯誤。 錯誤發生在cout語句中,這表明問題出在內存分配上。
我無法找出問題所在。 誰能解釋並建議我如何更正下面的代碼?
#include<iostream>
using namespace std;
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
};
void insert(TreeNode *root, int data){
TreeNode *newNode = new TreeNode;
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
if(root==NULL){
root = newNode;
return;
}
}
int main(){
TreeNode *root=NULL;
insert(root,10);
cout << root->data << endl;
}
您將“ root”參數作為值傳遞,這意味着當您更改它時,您僅更改它的本地副本。 這意味着當您將root設置為有效值時,它不會更改main中的root。 由於root的值為NULL,因此會產生分段錯誤。
您可以通過返回插入的節點或使用引用來修復它。 帶有參考:
void insert(TreeNode*& root, int data){
TreeNode *newNode = new TreeNode;
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
if(root==NULL){
root = newNode;
return;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.