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.
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;
The problem might be that you never add your new node to the tree.
parent = new treeNode;
parent->data=num;
parent->left=NULL;
parent->right=NULL;
temp=parent;
You assign your new node to temp and parent, which are temporary variables and therefore don't exist outside of the function. What you have to do is assign your new node to either parent->left or parent->right, depending on which side your new input lies, in order to link it into the the tree. Therefore what you want to do is something like the following:
temp = new treeNode;
temp->data=num;
temp->left=NULL;
temp->right=NULL;
if(num < parent->data)
parent->left = temp;
else
parent->right = temp;
Algo
- if root == null Create new node assign to Root
- Keep iterating based on comparison with rootNode until reach any leaf Node
- check if num <= parent(leaf) Insert into left ELSE insert into right
Code
private void insertItrInBST(int num){
Node temp = root,parent = root;
if(root == null){
root = getNewNode(num);
}else{
temp = root;
while(temp != null){
if(num <= root.data){
parent = temp;
temp = temp.left;
}else{
parent = temp;
temp = temp.right;
}
}
Node newNode = getNewNode(num);
if(num <= parent.data){
parent.left = newNode;
}else{
parent.right = newNode;
}
}
}
来源:https://stackoverflow.com/questions/6637830/non-recursive-add-function-in-a-binary-tree-using-c