Search code examples
c++binary-search-treeheap-memory

Binary Search Tree insert not creating data on the heap even though the "new" keyword is used


Im having an issue with my code as its not inserting a node on the heap. I GDBed the code to see what was happening and i found out that its inserting the data correctly and making a node but after the function ends the node is destroyed and its reset to NULL. So I'm thinking that its not correctly being created on the heap but i use the "new" keyword so I'm pretty stumped. Anyways heres my code any help would be much appreciated.

int BST::insert(int data)
{
int isSuccess;
if(head == NULL)
{
    head = new BSTNode(data);
    return data;
}   
else
{   
    if(data < head->data)
        isSuccess = insertTreeNode(head->left,data);
    else if(data > head->data)
        isSuccess = insertTreeNode(head->right,data);
    else
        return 0;
}

return isSuccess;
}

Here is a aux function

int BST::insertTreeNode(BSTNode* temp,int data)
{
int returnVal = data;
if(temp == NULL)
    temp = new BSTNode(data);
else if(data < temp->data)
    returnVal = insertTreeNode(temp->left,data);
else if(data > temp->data)
    returnVal = insertTreeNode(temp->right,data);
else
    returnVal = 0;
return returnVal;
}

Here is h file for BSTNode

#ifndef BSTNODE_H
#define BSTNODE_H
#include <iostream>
using namespace std;

class BSTNode
{
public:
    BSTNode* left;
    BSTNode* right;
    int data;
    BSTNode(int);
private:

};
#endif

Sorry about the formatting. Also head is a type BSTNode*


Solution

  • What's happening is that you are changing the pointer inside your function but it is not seen outside your function.

    Change your function signature to this:

    int BST::insertTreeNode(BSTNode * & temp,int data)
    

    I won't comment on any other portion of your code.