Your tree should store the word
and the number of times it occurs. To process the input file, find (or insert) the word in the tree. Then increment the count. To print the unique words, traverse the tree and print the entries where count == 1.
bInsert would be cleaner if it took a reference to the pointer:
1 2 3 4 5 6 7 8 9 10 11
|
void
bInsert(string c, node * &t)
{
if (t == NULL)
t = new node(c);
else if (t->word <= c)
bInsert(c, t->right);
else
bInsert(c, t->left);
}
|
But as you'll see below, you actually don't need it.
I always find it helpful in binary trees to write this function:
1 2 3 4 5 6 7
|
// Find the node that contains c, and return a reference to the pointer
// to it. If c doesn't exist in the tree, return a reference to the pointer
// where it would go.
node * &find(string c, node * &t)
{
...
}
|
Then for this assignment, you want a function that finds the word in the tree, or inserts it if it isn't there already:
1 2 3 4 5 6 7 8
|
node *findOrAdd(string c, node * &t)
{
node * &p = find(c, t);
if (p == nullptr) {
p = new node(c);
}
return p;
}
|
Now counting the number of times a word occurs is easy. This code assumes that the input comes from cin:
1 2 3 4 5 6 7
|
node *T = nullptr;
string word;
while (cin >> word) {
node *p = findOrAdd(word, T);
p->count++;
}
|
Recall that I said you should include the count in node. Be sure to initialize the count to zero in the constructor!
Last of all, the number of distinct words in a tree is:
the number of distinct words in the right branch,
plus the number in the left branch,
plus 1, if the current node represents a word occurred just once.