Vineet
Vineet

Reputation: 1

Binary tree code below is giving segmentation fault. Can anyone explain why?

I am trying to code a binary tree. At first I check if the root is empty, if so I assign the data to root. But the code is giving segmentation fault. The error is occurring in the cout statement, which suggests that the problem is with memory assignment.

I am unable to figure out whats wrong. Can anyone please explain and suggest how I can correct the code below?

#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;

}

Upvotes: 0

Views: 28

Answers (1)

svenslaggare
svenslaggare

Reputation: 438

You are passing the "root" parameter as value, meaning when you change it you only change a local copy of it. This means when you set root to a valid value, it doesn't change root in main. As root has a value of NULL it gives a segmentation fault.

You can either fix it by returning the inserted node or using references. With references:

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;
    }
}

Upvotes: 0

Related Questions