c - 搜索二叉树然后更新重复计数

标签 c recursion binary-tree

我正在编写一个从标准输入读取文件的程序。该文件在几行上有不同的名称,我试图避免在二叉树中输入重复的名称。我编写了一些代码只是为了确保将名称添加到节点并打印输入文件中的所有名称。我能够成功地做到这一点,但现在我试图返回并避免输入两次名称,但如果多次找到该名称则更新计数。所以我对如何搜索这个二叉树以及在什么时候进行搜索感到困惑,当我从文件中获取每个名称时我是否进行搜索?这段代码的注释部分是我想要实现的部分

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node {
    char* name;
    int count;
    struct node* left;
    struct node* right;
};

struct node* addNode(char* string);
/*struct node* search(struct node* root, char* stringg);*/
void insert(struct node *root, char* stringgg);
void preorder(struct node *root);

int main()
{
    char buffer[20];
    struct node *root = NULL;

    while( fgets(buffer, sizeof(buffer), stdin) != NULL )
    {
        count = 0;

        if(root == NULL)
            root = addNode(buffer,&count);
        else
          /*root = search(root,buffer) is this correct here? search for the name as it comes in, if found in search root changes to place where it was found*/
        insert(root,buffer);

    }
    preorder(root);

}

struct node* addNode(char* string,int *countptr)
{
    struct node *temp = malloc(sizeof(struct node));
    temp->name = malloc(strlen(string) + 1);
    strcpy(temp->name,string);
    temp->count = *count + 1;

    temp->left = NULL;
    temp->right = NULL;
    return temp;
}

/*struct node* search(struct node* root, char* stringg);*/
  {
       if(strcmp(root->name,stringg) == 0);/*if found, return adress of where it was found*/
       return root;
       /*unsure of other conditions to test for and what to change how do i check the left and right side and recursivly check until the whole tree is searched? */

  }

void insert(struct node *root, char* stringgg)
{
    if(strcmp(stringgg,root->name) < 0)
    {
        if(root->left == NULL)
            root->left = addNode(stringgg);
        else
            insert(root->left, stringgg);
    }
    else
    {
        if(root->right == NULL)
            root->right = addNode(stringgg);
        else
            insert(root->right,stringgg);
    }
}

void preorder(struct node *root)
{
    if(root == NULL)
        return;
    printf("%s",root->name);
    preorder(root->left);
    preorder(root->right);

}

我希望这样,当我打印这些节点时,我不会得到重复的名称,而是得到该名称在文件中重复的次数。所以如果我有 std 正在读取的文件

bob
john
dylan 
bob
dylan 
dylan

当我完成树的构建并打印后,通用表格将是

bob 2
dylan 3
john 1

最佳答案

只需让您的插入函数处理 == 0通过增加节点计数而不是添加新节点的情况。 (您已经处理了 > 0< 0 ,只需添加最后一个案例。)

关于c - 搜索二叉树然后更新重复计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25027603/

相关文章:

javascript - 需要帮助理解将 BST 转换为排序数组的算法中的错误

algorithm - 无限完整二叉树中两个节点之间的最短路径?

c - 我无法从递归函数中正确返回

c++ - "&"和通过引用传递

java - 有重复的 BST

c++ - poll返回0但read不阻塞

在 C 程序中检查文件属性

objective-c - Objective C 类方法与 C 函数

android - 在 Android 上运行 C 代码而不编译整个树

php - 在递归函数 php 中重新启动第一个循环