二叉树中的搜索关键字

问题描述

我遇到的问题是,对于某些键,我的函数有效,但对于某些键却无效。如果树中没有带有该键的元素,则该函数应返回一个指向key == givenKeyNULL的节点的指针。这是结构,下面是函数。

typedef struct node
{
    int key;
    struct node *l,*r;
}NodeT;

NodeT *search(NodeT *root,int givenKey)
{
    if(root == NULL || root->key == givenKey)
        return root;
    search(root->l,givenKey);
    search(root->r,givenKey);
}

这是main中函数的调用:

    NodeT *q = search(root,9);
    NodeT *r = search(root,7);
    printf("%p\n%p\n",q,r);

这是给定的二叉树:(例如q获得正确的地址,但是r将是NULL,即使其中包含带有key = 7的元素我们的二叉树。

enter image description here

如果您告诉我什么地方出了问题,我将不胜感激,因为我尝试了很多次更改功能,但是没有成功。我什至使用调试器浏览了我的代码,但似乎没有太大帮助。预先谢谢你!

解决方法

检查root是否包含密钥,并递归检查子级。 如果没有找到带有密钥的节点,它将返回NULL

NodeT* search(NodeT* root,int givenKey)
{
    if (!root)
        return NULL;
    else if (root->key == givenKey)
        return root;

    NodeT* search_child_result = NULL;
    if (root->l)
    {
        search_child_result = search(root->l,givenKey);
        if (search_child_result)
            return search_child_result;
    }

    if (root->r)
    {
        search_child_result = search(root->r,givenKey);
        if (search_child_result)
            return search_child_result;
    }

    return search_child_result;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...