I've been working on a twenty questions game for my last project of the year. I have the game running fine. It starts with only a few nodes, but learns as it goes along...if it guesses wrong, it asks you what you are, and a question that it should ask to determine that. It then builds a new node and adds it to the tree. The leaf nodes contain the animals(its a taxonomic game), and the nodes above contain the questions in their data field.
We're supposed to save the game state, so that the next time you run it, it will remember all the new nodes you have added. I'm having a very hard time with this. What I decided to do is to use a preorder traversal and:
1) print root node's data
-if node->left is not NULL, print a 1 to the next line
-else print a zero
2) process left
3) process right
Here is the code i'm trying:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
void write_to_file(binary_tree_node<string>* pointer, fstream &file)
{
file << pointer->data() << endl;
if (pointer->left()!= NULL)
{
file << "1" << endl;
write_to_file(pointer->left(), file);
}
else
{
file << "0" << endl;
}
if (pointer->right()!=NULL)
{
file << "1" << endl;
write_to_file(pointer->right(),file);
}
else
{
file << "0" << endl;
}
}
| |
if I run it with just the default couple of nodes, here is the output:
1 2 3 4 5 6 7 8 9 10 11 12
|
Let's play!
You pretend to be an animal, and I try to guess what you are.
Think of an animal, then press the return key.
Are you a mammal? Please answer: [Yes or No]
yes
Are you bigger than a cat? Please answer: [Yes or No]
no
My guess is Mouse. Am I right? [Yes or No]
yes
I knew it all along!
Shall we play again? [Yes or No]
| |
All of the nodes are saved to the file, but I'm getting extra numbers for the leaf nodes.
here is the text file I get:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
Are you a mammal?
1
Are you bigger than a cat?
1
Kangaroo
0
0
1
Mouse
0
0
1
Do you live underwater?
1
Trout
0
0
1
Robin
0
0
| |
I'm pretty sure that the extra values are getting printed when the function returns from a recursive call, but I'm having trouble figuring out where.