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

时间:2014-07-30 01:52:54

标签: c recursion binary-tree

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

#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

1 个答案:

答案 0 :(得分:0)

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