在在C二叉搜索树词频? [英] word frequency in a binary search tree in c?

查看:104
本文介绍了在在C二叉搜索树词频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我都数不过来有多少次在二叉树存在一个字,我不能这样做,我怎么能做到这一点?这里是我的code;

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

我有一个包含不止一次有些话.txt文件,我需要指望有多少次在这棵树的存在的话。

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.

推荐答案

您code不工作,因为你不插入重复值。由于重复的值将返回的strcmp()为0,他们没有被首先加入。因此,在insertNode()函数,你就需要考虑其他情况也是如此:

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

事实上,else子句应该简单地增加计数中(如(* treePtr) - >计数+ = 1;)。此外,请确保您的初始温度结构中的值初始化为1你MALLOC树节点后(如TEMP->计数= 1;)。

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;").

这篇关于在在C二叉搜索树词频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆