Insert C ++ binary search tree

Maybe I asked a million times earlier, but I just can’t understand what is wrong with this. I did not want to use any code on the Internet, so I was just trying to program what was on my mind. Either this or my print function is incorrect. Is there something wrong with the code below?

void addNode(int value)
    {
        Node* newNode=new Node;
        newNode->data=value;
        if(root==NULL)
            root=newNode;
        else {
            Node* temp=root,*parent;
            while(temp!=NULL)
            {
                parent=temp;
                if(temp->data == value)
                    return;
                else if(temp->data < value)
                    temp=temp->left;
                else 
                    temp=temp->right;
            }
            temp=newNode;
        }
    }
+3
source share
1 answer
temp=newNode;

This assigns a local variable to the pointer, which is discarded when the function returns, losing the new node. Instead, you want to assign it to a pointer inside the tree; maybe something like:

if (temp->data < value) {        // If the new node should be to the left
    if (temp->left) {            //   If there is a left subtree
        temp = temp->left;       //      Move into the left subtree
    } else {                     //   Otherwise
        temp->left = newNode;    //      Insert the new node there
        return;                  //      Done.
    }
}

as well as for temp->rightif value < temp->data.

also:

if (temp->data == value) 
    return;

You have a memory leak there; You must delete newNodebefore return.

+6
source

All Articles