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.