2015-02-08 42 views
0

我想編碼一個二叉樹。首先我檢查根是否爲空,如果是的話,我將數據分配給根。但是代碼給出了分段錯誤。錯誤發生在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; 

} 

回答

0

您正在傳遞「root」參數作爲值,這意味着當您更改它時,只會更改它的本地副本。這意味着當您將root設置爲有效值時,它不會更改main中的根目錄。由於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; 
    } 
} 
相關問題