簡體   English   中英

二叉搜索樹根節點保持NULL

[英]Binary Search Tree root node stays NULL

出於某種原因,我的根節點始終保持 NULL 並且沒有添加任何內容。 我不確定為什么,並且想知道是否有人可以指導我做錯了什么。 我正在嘗試讀取一個文件並根據我得到的數字對每個單詞執行不同的操作。 如果它是 1,我試圖將這個詞插入二叉樹,除非它是重復的,在這種情況下,我試圖讓頻率上升 1。如果它是 2,我希望能夠打印出單詞出現的深度和次數。 最后,我想根據最頻繁到最少的順序顯示單詞。 我現在陷入困境的部分是根節點始終保持為 NULL,因此我無法構建我的樹,我也不知道問題到底是什么。

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

#define MAXSIZE 50

typedef struct node
{
    int depth;
    int frequency;
    struct node *left, *right;
    char word[MAXSIZE];
} node;


node* insert(node* root, char newWord[MAXSIZE])
{
    node *temp;
    printf("insert Function is being called\n %s\n", newWord);
    if(root == NULL)
    {
        temp = (node*) malloc(sizeof(node));
        temp->frequency = 1;
        temp->depth = 1;
        temp->left = NULL;
        temp->right = NULL;
        strcpy(temp->word, newWord);
        root = temp;
        printf("You should only recieve this message once.\n");
    }
    else if(strcmp(newWord, root->word)<0)
    {
        printf("Word being added towards left\n");
        insert(root->left, newWord);
        root->depth +=1;
    }
    else if(strcmp(newWord, root->word)>0)
    {
        insert(root->left, newWord);
        printf("Word being added towards right\n");
        root->depth +=1;
    }
    else if(strcmp(newWord, root->word)==0)
    {
        printf("Word being duplicated");
        root->frequency +=1;
    }
    return(root);
}

int inOrder(node* root)
{
    if(root != NULL)
    {
        inOrder(root->left);
        printf("BADAM %s\t", root->word);
        printf("%d\n", root->frequency);
        inOrder(root->right);
    }
}



void main()
{
    FILE *infile;
    FILE *outfile;
    char string[MAXSIZE];
    int i, c, n, j, k;
    node *root;
    root = NULL;
    infile = fopen("in.txt", "r");
    fscanf(infile, "%d\n", &n);
    for(i=0;i<n;i++)
    {
        printf("%d\n", i);
        fscanf(infile, "%d %s\n", &c, string);
        printf("the action is %d\n", c);
        switch (c)
        {
            case 1:
                printf("insert %s\n", string);
                insert(root, string);
                break;
            case 2:
                printf("print frequency of %s\n", string);
                break;
            default:
                printf("error in input\n");
                break;
            inOrder(root);
        }
    }
}

您需要將函數插入返回的指針分配給指針根

root = insert(root, string);

在你需要寫的函數中

root->left = insert(root->left, newWord);

而不是在此代碼片段中使用 root->left

else if(strcmp(newWord, root->word)>0)
{
    insert(root->left, newWord);
    //...

你需要使用指針 root->right

else if(strcmp(newWord, root->word)>0)
{
    root->right = insert(root->right, newWord);
    //...  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM