如何按字母顺序排序BST作为频率排序树?

时间:2015-12-27 10:59:31

标签: c++ tree unique word

根据我的家庭作业,我正在研究二元树。分配很简单,从输入文本文件中读取单词并创建包含频率数据的BST。

我只是搜索它并创建了一个alphebetically命令BST的实现,它对我很有用。

但我一直在努力的问题是,Rank each unique word in descending order of frequency.

树正在使用alpabetical排序,通过比较字符串并创建与之相关的节点......那么我如何继续使用它们的频率?我应该使用按字母排序的树元素创建一个频率平衡的新树吗?

任何帮助都会受到赞赏,非常感谢提前!

但我该如何保持计数

TreeNode.h:

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

class treeNode
{
public:
    char data[55];
    int count;
    struct treeNode *leftPtr, *rightPtr;
};



typedef struct treeNode TreeNode;
typedef TreeNode *TreeNodePtr;

void insertNode(TreeNodePtr *treePtr, char word[]);
void alphabetic(TreeNodePtr treePtr);
int sizeOfTree(TreeNodePtr treePtr);

TreeNode.cpp:

# include "treeNode.h"

void::insertNode(TreeNodePtr *treePtr, char word[55]){
    TreeNode *temp = NULL;
    if (*treePtr == NULL)
    {
        temp = (TreeNode *)malloc(sizeof(TreeNode));
        temp->count = 1;
        temp->leftPtr = NULL;
        temp->rightPtr = NULL;
        strcpy(temp->data, word);
        *treePtr = temp;
    }
    else if (strcmp(word, (*treePtr)->data) < 0)
    {
        insertNode(&((*treePtr)->leftPtr), word);

    }
    else if (strcmp(word, (*treePtr)->data) > 0)
    {
        insertNode(&((*treePtr)->rightPtr), word);
    }
    else
    {
        (*treePtr)->count += 1;
    }
}


void::alphabetic(TreeNodePtr treePtr)
{
    if (treePtr != NULL)
    {
        alphabetic(treePtr->leftPtr);
        printf("%s\t", treePtr->data);
        printf("%d\n", treePtr->count);
        alphabetic(treePtr->rightPtr);
    }
}

int::sizeOfTree(TreeNodePtr treePtr){
    if (treePtr == NULL)
        return 0;
    else
        return(sizeOfTree(treePtr->leftPtr) + 1 + sizeOfTree(treePtr->rightPtr));
}

主要功能:

int main()
{
    /*reading strings from the file and add them to the tree*/

    int totalSize = 0;
    char first[55];
    FILE *fp1;
    TreeNodePtr rootPtr = NULL;
    int c;
    //fp1 = fopen("%FILENAME%", "r");
    fp1 = fopen("FILENAME%", "r");
    do
    {

        c = fscanf(fp1, "%s", first);

        if (c != EOF)
        {
            //printf(first);
            insertNode(&rootPtr, first);

        }
    } while (c != EOF);

    fclose(fp1);
    //printf("%s", rootPtr->rightPtr->leftPtr->data);
    alphabetic(rootPtr);

    printf("%d\n",sizeOfTree(rootPtr));
    system("PAUSE");
    return 0;
}

更新:我直接要求使用BST作为数据结构,不应使用其他地图,散列或C ++ STL结构。

1 个答案:

答案 0 :(得分:0)

不会要求您重新排列节点 in-tree 。要求您提取最常见的单词。

原则很简单。每个任务的一张地图,如:

std::map<string, int> wordmap; // this is your bst.
while(in>>word){
   wordmap[word]++;
}

std::map<int, string, std::greater<int>> countmap;

for(auto word_and_count: wordmap){
   countmap[wordmap.second] = wordmap.first;
}

请注意,这不是正常工作的代码。它旨在显示该过程。

相关问题