Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Search Tree Insertion C++

Maybe asked million times before but I simply cannot understand what's wrong with this. I didn't want to use any code on the internet so I've just tried to program what's on my mind. Either this or my print function is wrong. Is there anything 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;
        }
    }
like image 338
Ali Avatar asked Sep 23 '26 19:09

Ali


1 Answers

temp=newNode;

This assigns the pointer to a local variable, which is discarded when the function returns, losing the new node. Instead, you want to assign it to a pointer within the tree; perhaps 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.
    }
}

and likewise for temp->right if value < temp->data.

Also:

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

You have a memory leak there; you should delete newNode before returning.

like image 192
Mike Seymour Avatar answered Sep 26 '26 09:09

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!