Non-recursive add function in a binary tree using c++

GKED picture GKED · Jul 10, 2011 · Viewed 8.1k times · Source

I am writing an Add function to add nodes to a binary tree non recursively. I have run into the problem of only being able to produce one level deep binary tree. I debugged it and I know where the problem is but can't figure out how to fix it. Maybe fresh pair of eyes will see something i dont... The problem is that my temp node is being reset to the root value every new function call and hence, adding nodes linearly. Anyways, here is the function:

   void BinaryTreeNonRec::add(int num){
        treeNode *temp, *parent;

        if (root==NULL) {
            root = new treeNode;
            root->data=num;
            root->left=0;
            root->right=0;
            temp=root;
            printf("value is root \n");
        } else {
            temp=root;
            while (temp!=NULL) {
                if (num <= temp->data){
                    parent = temp;
                    temp=temp->left;
                    //root =temp;
                    printf("value is to the left \n");
                } else {
                    parent =temp;
                    temp=temp->right;
                    //root=temp;
                    printf("value is to the right \n");
                }               
            }   
            parent = new treeNode;
            parent->data=num;
            parent->left=NULL;
            parent->right=NULL;
            temp=parent;
        }   
}

Thanks for any kind of help.

Answer

bcsanches picture bcsanches · Jul 10, 2011

You are not adding the new node to the tree, just running down the tree and filling parent with a new node, but never adding it to the tree, change below code:

parent = new treeNode;
parent->data=num;
parent->left=NULL;
parent->right=NULL;
temp=parent;

To:

treeNode *newNode = new treeNode;
newNode->data = num;
newNode->left = NULL;
newNode->right = NULL;

//Now insert the new node BELOW parent
if(num <= parent->data)
    parent->left = newNode;
else
    parent->right = newNode;