c - C 中按字母顺序排序的二叉搜索树?

标签 c binary-search-tree

我如何开发一个程序,从文本文件中读取单词并使用这些单词创建按字母顺序排序的二叉搜索树?这是我的代码

 #include "stdio.h"
#include "stdlib.h"
#include "string.h"

struct treeNode {
       char data[20];
       int count;
       struct treeNode *leftPtr, *rightPtr;
 };

int number;

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);
        insertNode(&rootPtr,first);




    }while(c!=EOF);


    fclose(fp1);

    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;
        temp->data[20] =  word[20];
        *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{
        number++;
    }
}

/*for sorting alphabetically*/
void alphabetic(TreeNodePtr treePtr){
    if(treePtr!=NULL){
        alphabetic(treePtr->leftPtr);
        printf("%3d\n",treePtr->leftPtr);
        alphabetic(treePtr->rightPtr);
    }
}

当我有一个包含 4 个单词的 .txt 时,我的程序只写入四个 0 作为输出。

最佳答案

这一行是错误的:

    temp->data[20] =  word[20];

它将单个字符从一个无效位置复制到另一个无效位置。

将其更改为:

    strcpy(temp->data, word);

因为您要复制字符串。

这行看起来也有问题:

    printf("%3d\n",treePtr->leftPtr);

我猜你想在这里打印 data 字符串的内容,所以它应该是:

    printf("%s\n", treePtr->data);

或者如果您想要整数 count 元素,则为:

    printf("%d\n", treePtr->count);

关于c - C 中按字母顺序排序的二叉搜索树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18536778/

相关文章:

java - 为什么我的解决方案无法找到二叉树的最小深度?

c - 内存分配和更改值

c - 扫描指针数组问题

recursion - 这个检查树是否是 BST 的方法有什么问题

c - 打印二叉搜索树,段错误错误 11

c++ - 如何修复模板 BST 类的对象初始化?

c - 我尝试创建以相反顺序显示其给定参数的代码,但为什么它的代码告诉我段错误?

c - C 中的矢量化 Trig 函数?

c - 如何在c中使用结构体作为变量?

java - 是否需要构造函数来初始化静态变量?