When i step into my Insert method it does what it should, but once i call my preOrder function it only prints the last integer from the file. I tried using '&' thinking it was a pass by reference issue but did not work.
Also i used a node*temp to fill out the tree so that the node*root would stay the same(i.e. just like using head node and a iter node in a linked list ) but i still got the same issue.
When i step into my Insert method it does what it should
Wrong. Insert is 99% of the problem. It only ever saves over the root value. You need to look over this more carefully.
The other 1% of the problem, which you haven't encountered since you can't get a tree, is that you print the root before you print the left side of the tree. You need to switch the positions of lines 19 & 20.
int myinteger = 5;
int *intpointer = &myinteger;
std::cout << intpointer << std::endl; //prints memory address
std::cout << *intpointer << std::endl; //prints the value of the pointer that intpointer is pointing to
The other 1% of the problem, which you haven't encountered since you can't get a tree, is that you print the root before you print the left side of the tree.
What the OP is doing is correct for pre-order traversal. Printing the left side of the tree first would be in-order traversal.
Your main program can be simplified. To read the file just do:
1 2 3
while (infile >> key) {
insert(key, root);
}
This takes advantage of the fact that while() is expecting a bool and std::stream has a convert-to-bool operator that returns stream.good();
The problem with inset() is lines 10 and 21. THey should be tmp->left->data = key;
and tmp->right->data = key;
respectively because you're setting the key of the NEW node.
But all that duplicated code in insert() should make you uncomfortable. Is there a way to simplify it? Since you're passing the pointer by reference, just let insert() handle the case where the pointer is NULL. If you do that, the replicated code goes away:
i set my root to Null before i enter my while loop, But THANK YOU i will use your way..they both work, not sure why you have to use & though if i declare node*root in global???