简体   繁体   中英

Finding the Most Common Words in a Binary Search Tree

I'm writing a function to output the most common word in a Binary Search Tree but it outputs the word in the top of the bst in alphabetical order rather than most common word.

for example:

Input: abc abc abc abc xyz xyz xyz xyz xyz xyz

Output: abc

I really don't know what the issue is, any help would be greatly appreciated.

void WordAnalyzer::findCommon(TreeNode* root) {
    if (root != NULL) {
        findCommon(root->left);
        if (prev != NULL) {
            if (root->data == prev->data) {
                currCount++;
            }
            else {
                currCount = 1;
            }
        }

        if (currCount > maxCount) {
            maxCount = currCount;
            maxWord = root->data;
        }
        prev = root;
        findCommon(root->right);
    }
}

string WordAnalyzer::getMostCommonWord() {
    findCommon(root);
    return maxWord;
}

It is not clear from the code how and where currCount is initialized, but if it is not initialized explicitly before this code runs, you have an undefined behavior.

When looking at the first (leftest) element in your BST, you set prev = root , but you do not set currCount , then when you visit the next element, you increase currCount by 1, but you never gave it an initial value, and it can contain basically any "garbage" value.

Just create a map with key as "word" and value as "count". Traverse the BST using any traversal (like Inorder), and increment the counts for corresponnding "word" in map. Then when whole traversal is over, check in your main function, the word with the most count in Map.

Here is a quick reference if you are not familiar with the Map data structure. http://www.cplusplus.com/reference/map/map/insert/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM