我必须计算一个单词在二叉树中存在多少次,我不能这样做,我该怎么做?这是我的代码;
#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 文件,其中不止一次包含一些单词,我需要计算一个单词在这棵树中存在多少次。