找不到

时间:2018-06-16 01:37:35

标签: c return structure binary-tree

如何在找到树节点时返回树节点?

所以,我有一个二叉树,当我在树中搜索我搜索到的内容时,我想返回指向该节点的指针,所以我可以在其他函数中使用该节点。有我的搜索功能:

Tnode *Tsearch(Tnode *r, char *word) {
    if(r == NULL) {
        printf("%s NOT FOUND\n", word);
        return NULL;
    }
    int comp = strcasecmp(r->word, word);
    if( comp == 0) {
        printf("%s FOUND\n", r->word);
        return r;
    }
    else if( comp > 0) {
        Tsearch(r->left, word);
    }
    else if( comp < 0) {
        Tsearch(r->right, word);
    }
    return 0;
}

我的问题是,当我尝试使用Tsearch函数的返回时,它不起作用,我真的无法理解为什么以及如何解决它。

我想从搜索功能使用返回节点的功能如下:

int Tsearch_ref(Tnode *r, char (*words)[30]) {
    if(r == NULL) {
        return 0;
    }
    printf("%s, %d", words[0], (int)strlen(words[0]));
    Tsearch(r,words[0]);
    auxT = Tsearch(r,words[0]);
    Lnode *aux = auxT->head;
    printf("Title: %s\n", ((Book *)aux->ref)->title);
    while(aux != NULL) {
        aux_arr[i].ref=aux->ref;
        printf("Title: %s\n", ((Book *)aux_arr[i].ref)->title);
        printf("%p\n", &(aux_arr[i].ref));
        aux = aux->next;
        i++;
    }
}

这个函数不完整,因为我试图解决返回问题,但基本上我想把那个里面有一个列表的树节点放到一个临时数组中。

结构如下:

typedef struct {
    char *title;
    char isbn13[ISBN13_SIZE];
    char *authors;
    char *publisher;
    int year;
} Book;

typedef struct lnode {
    struct lnode *next;
    void *ref;
} Lnode;


typedef struct tnode {
    struct tnode *left;
    struct tnode *right;
    char *word;
    Lnode *head;
} Tnode;

这是我在StackOverflow中的第一个问题,所以如果您需要任何更多信息,我会明显提供它。

提前致谢!

2 个答案:

答案 0 :(得分:1)

您需要更改对Tsearch的递归调用以实际返回找到的节点。所以,而不是这段代码:

""

这样做:

else if( comp > 0) {
    Tsearch(r->left, word);
}
else if( comp < 0) {
    Tsearch(r->right, word);
}

请注意,如果树很深,则可能会耗尽整个调用堆栈并抛出异常。

答案 1 :(得分:1)

为什么不在中使用循环?

Tnode *Tsearch(Tnode *r, char *word) {
    Tnode *cur = r;
    int comp;
    while (cur != NULL)
    {
        if ((comp = strcasecmp(cur->word, word)) == 0)
        {
            printf("%s FOUND\n", cur->word);
            return cur;
        }
        else if (comp > 0)
        {
            /* Move to the left child */
            cur = cur->left;
        }
        else
        {
            /* Move to the right child */
            cur = cur->right;
        }
    }
    printf("NOT FOUND\n");
    return NULL;
}