Darcy Oakie
Darcy Oakie

Reputation: 39

C++ program implementing tree stops working when a node is inserted and I can't understand why

here is my code. after reading T the program reads the first input data and stops working. message "Unhandled exception at 0x00844D30 in tree.exe: 0xC0000005: Access violation reading location 0x00000000." is shown. I included iostream and stddef.h libraries.

class Node{
public:
    int data;
    Node *left, *right;
    Node(int d){
        data = d;
        left = right = NULL;
    }
};

class Solution{
public:
    Node* insert(Node* root, int data){
        if (root = NULL){
            return new Node(data);
        }
        else{
            Node* cur;
            if (data <= root->data){
                cur = insert(root->left, data);
                root->left = cur;
            }
            else{
                cur = insert(root->right, data);
                root->right = cur;
            }
            return root;
        }
    }

};

int main(){
    Solution myTree;
    Node* root = NULL;
    int T, data;
    cin >> T;
    while (T-->0){
        cin >> data;
        root = myTree.insert(root, data);
    }

    return 0;
}

Upvotes: 0

Views: 58

Answers (2)

javaDeveloper
javaDeveloper

Reputation: 1439

The condition should be

if (root==NULL)

    #include <iostream>
#include <stddef.h>
using namespace std;
class Node{
public:
    int data;
    Node *left, *right;
    Node(int d){
        data = d;
        left = right = NULL;
    }
};

class Solution{
public:
    Node* insert(Node* root, int data){
        if(root == NULL){
            return new Node(data);
        }
        else{
            Node* cur;
            if (data <= root->data){
                cur = insert(root->left, data);
                root->left = cur;
            }
            else{
                cur = insert(root->right, data);
                root->right = cur;
            }
            cur->left=cur->right=NULL;
            return root;
        }
    }

};

int main(){
    Solution myTree;
    Node* root = NULL;
    int T, data;
    cin>>T;
    while (T-->0){
        cin>>data;
        root = myTree.insert(root, data);
    }

    return 0;
}

Upvotes: 1

Flocke
Flocke

Reputation: 1035

This if will always go into the else part. Because you assign NULL to the variable root and then check the value. It should be root == NULL

        if (root = NULL){
            return new Node(data);
        }
        else{
            Node* cur;
            if (data <= root->data){
                cur = insert(root->left, data);
                root->left = cur;
            }
            else{
                cur = insert(root->right, data);
                root->right = cur;
            }
            return root;
        }

Upvotes: 1

Related Questions