如何将按字母顺序排列的BST排序为按频率排序的树
How to sort alphabetically ordered BST as frequency ordered tree?
根据我的家庭作业,我正在研究二进制树。任务很简单,从输入文本文件中读取单词,并创建一个包含频率数据的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;
}
请注意,这不是工作代码。它旨在展示这个过程。
相关文章:
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何在BST的这个简单递归实现中消除警告
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 下面是排序算法O(n)吗
- 尝试使用C++中的模板进行BST排序,但在使用随机字符串进行测试时不起作用
- C bST删除节点会破坏排序算法
- 将 BST 转换为排序的双向链表
- 将值插入到两个排序不同的 BST 中
- 如何将按字母顺序排列的BST排序为按频率排序的树
- 如何使用C++中的堆栈、队列或 BST 对文件中的记录进行排序