word frequency in a binary search tree in c?

邮差的信 提交于 2019-12-25 19:07:18

问题


i have to count how many times a word exists in the binary tree and i couldn't do this ,how can i do this? here is my code ;

#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) < 0)
  {
    insertNode(&((*treePtr)->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("%s\n", treePtr->data);

    alphabetic(treePtr->rightPtr);
  }
}

i have a .txt file which contains some words more than once,and i need to count how many times a word exists in this tree.


回答1:


Your code does not "work" because you are not inserting duplicate values. Since the duplicate values would return strcmp() as 0, they are not being added in the first place. Thus in the insertNode() function, you would need to consider the else case as well:

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

In fact, the else clause should simply increment the count as in (as in "(*treePtr)->count += 1;"). Also, make sure you initialize the value to 1 in the initial temp structure after you malloc the TreeNode (as in "temp->count = 1;").



来源:https://stackoverflow.com/questions/18538598/word-frequency-in-a-binary-search-tree-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!