如何将按字母顺序排列的BST排序为按频率排序的树

How to sort alphabetically ordered BST as frequency ordered tree?

本文关键字:排序 BST 频率 顺序 排列      更新时间:2023-10-16

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

我只是简单地搜索了一下,并创建了一个Alphebyly订购的BST的实现,它对我来说非常有效

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

该树通过比较字符串并创建与之相关的节点来使用Alpabential排序。。。那么我怎样才能保持它们的频率呢?我应该创建一个新的树作为频率平衡使用人工排序的树元素吗?

如有任何帮助,我们将不胜感激,提前表示感谢!

但是我该如何保持计数

树节点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);

树节点.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("%st", treePtr->data);
        printf("%dn", 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("%dn",sizeOfTree(rootPtr));
    system("PAUSE");
    return 0;
}

更新:我被直接要求使用BST作为数据结构,不应该使用其他映射、哈希或C++STL结构。

您不会被要求重新排列树中的节点。你被要求提取最常见的单词。

原理很简单。每个任务一张地图,类似于:

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;
}

请注意,这不是工作代码。它旨在展示这个过程。