Binary Tree Insertion help

jmcoreymv

Diamond Member
Oct 9, 1999
4,264
0
0
Im trying to make a program which reads a list of Id and Inv value pairs from a txt file and then creates a binary tree
Here are the 3 main functions and the problem is that some of the id/inv pairs are doubled when i print it out. I dont know whether the print function is doubling the values or the insert function is doubling the values. Also it is only psuedo ordering them. If anyone sees any blairing errors, please point them out, thanks.

void insert(treePtr &p,int id,int inv){
if(p==NULL)
{
p=new treeNode(id,inv);
}
else if(id<p->id)
{
if(p->left==NULL)
p->left=new treeNode(id,inv);
else
insert(p->left,id,inv);
}
else if(id>p->inv)
{
if(p->right==NULL)
p->right=new treeNode(id,inv);
else
insert(p->right,id,inv);
}
}

void readFile(treePtr &tree)
{
int howMany;
int id,inv;
ifstream inFile("store.txt",ios::in);
inFile>>howMany;
for(int i=1;i<=howMany;i++)
{
inFile>>id>>inv;
insert(tree,id,inv);
}
}

void printTree(treePtr tree){
if(tree->left!=NULL)
{
printTree(tree->left);
}
cout<<tree->id<<" "<<tree->inv<<endl;
if(tree->right!=NULL)
{
printTree(tree->right);
}
cout<<tree->id<<" "<<tree->inv<<endl;
}

Heres the list of original numbers
23
3434 43
4332 23
1023 3
929 16
289 48
292 92
1034 49
294 39
291 32
1948 28
2912 29
2910 28
281 29
438 17
299 93
2819 92
1812 102
324 192
2918 292
928 29
978 2
482 39
279 29

Heres the output
279 29
279 29
281 29
281 29
289 48
291 32
291 32
292 92
294 39
299 93
324 192
324 192
299 93
438 17
482 39
482 39
928 29
928 29
438 17
294 39
292 92
289 48
929 16
978 2
978 2
929 16
1023 3
1034 49
1812 102
1812 102
1948 28
2819 92
2819 92
2910 28
2910 28
2912 29
2918 292
2918 292
2912 29
1948 28
1034 49
1023 3
3434 43
4332 23
4332 23
3434 43
 

TangDN

Member
Mar 16, 2002
31
0
0
probably not the cause of your problem... maybe not even a problem if your compiler didn't pick it up ---

you've got an:
if()
else if()
else if()
..
but no else?

ahh. i hate programming.
 

ErikaSwift2000

Junior Member
Mar 20, 2002
3
0
0
Well, why are you printing values out twice in your printTree function?
It seems like it should be:

void printTree(treePtr tree){
if(tree->left!=NULL)
{
printTree(tree->left);
}

if (NULL != tree)
cout<<tree->id<<" "<<tree->inv<<endl;

if(tree->right!=NULL)
{
printTree(tree->right);
}
}


That is -- recurse down the left subtree then print out the value at the root then recurse down the right subtree.
Hope this helps!

Erika. :)
 

jmcoreymv

Diamond Member
Oct 9, 1999
4,264
0
0
Thanks! I just have trouble understanding how a recursion algorithm will run sometimes.