c/c++语言开发共享c中二进制搜索树中的字频率?

我必须计算二进制树中一个单词存在多少次,我不能这样做,我该怎么做? 这是我的代码;

#include "stdio.h" #include "stdlib.h" #include "string.h" struct treeNode { char data[20]; int count; struct treeNode *leftPtr, *rightPtr; }; int number = 1; typedef struct treeNode TreeNode; typedef TreeNode *TreeNodePtr; void insertNode(TreeNodePtr *treePtr, char word[]); void alphabetic(TreeNodePtr treePtr); int main() { /*reading strings from the file and add them to the tree*/ char first[20]; FILE *fp1; TreeNodePtr rootPtr = NULL; int c; fp1 = fopen("output.txt", "r"); do { c = fscanf(fp1, "%s", first); if (c != EOF) { insertNode(&rootPtr, first); } } while (c != EOF); fclose(fp1); printf("%s", rootPtr->rightPtr->leftPtr->data); //alphabetic(rootPtr); system("PAUSE"); } /*for adding nodes to tree*/ void insertNode(TreeNodePtr *treePtr, char word[20]) { TreeNode *temp = NULL; if (*treePtr == NULL ) { temp = (TreeNode *) malloc(sizeof(TreeNode)); temp->leftPtr = NULL; temp->rightPtr = NULL; strcpy(temp->data, word); *treePtr = temp; } else if (strcmp(word, (*treePtr)->data) leftPtr), word); } else if (strcmp(word, (*treePtr)->data) > 0) { insertNode(&((*treePtr)->rightPtr), word); } } /*traverse the tree*/ void alphabetic(TreeNodePtr treePtr) { if (treePtr != NULL ) { alphabetic(treePtr->leftPtr); printf("%sn", treePtr->data); alphabetic(treePtr->rightPtr); } } 

我有一个.txt文件,它不止一次包含一些单词,我需要计算这个单词中存在多少次单词。

    您的代码无法正常工作,因为您没有插入重复值。 由于重复值会将strcmp()返回为0,因此它们不会首先添加。 因此在insertNode()函数中,您还需要考虑else情况:

     else if (strcmp(word, (*treePtr)->data) < 0) { insertNode(&((*treePtr)->leftPtr), word); } else if (strcmp(word, (*treePtr)->data) > 0) { insertNode(&((*treePtr)->rightPtr), word); } else { //This is where the duplcate values should be inserted! } 

    实际上,else子句应该简单地增加计数(如“(* treePtr) – > count + = 1;”)。 另外,确保在malloc TreeNode之后将初始临时结构中的值初始化为1(如“temp-> count = 1;”)。

      以上就是c/c++开发分享c中二进制搜索树中的字频率?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/519226.html

      (0)
      上一篇 2020年12月5日
      下一篇 2020年12月5日

      精彩推荐