【发布时间】:2015-12-27 10:59:31
【问题描述】:
根据我的家庭作业,我正在研究二叉树。任务很简单,从输入文本文件中读取单词并创建一个包含频率数据的 BST。
我只是简单地对其进行了搜索并创建了一个按字母顺序排列的 BST 的实现,它对我来说非常有用。
但我一直在努力解决的问题是,Rank each unique word in descending order of frequency.
树通过比较字符串并创建与之相关的节点来使用字母排序...那么我该如何继续使用它们的频率呢?我应该通过使用按字母顺序排列的树元素来创建一个新的树作为频率平衡吗?
任何帮助将不胜感激,在此先感谢!
但是我应该如何保持计数
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 结构。
【问题讨论】:
-
void::alphabetic的语法是什么?这是您的实际代码吗? -
我正在使用这个函数来打印二叉树,因为它需要一个赋值标记。我已经在互联网上搜索了它并放置了一些与我的结构相关的小东西。这不完全一样。