开发者

Binary Search Tree error

开发者 https://www.devze.com 2023-03-29 09:16 出处:网络
I want to find minimum value in a Binary Search Tree. I have written below code. But when i call the function from main and I pribt 开发者_开发问答the return value, it is printing as 0 always.

I want to find minimum value in a Binary Search Tree. I have written below code. But when i call the function from main and I pribt 开发者_开发问答the return value, it is printing as 0 always.

cal you please help.

int findMinimumValue(struct tnode* node)
{
int min=node->data;
if(node->lchild==NULL)
{
   return min;
}
else
    findMinimumValue(node->lchild);
}


Looks like you're not actually returning the value of your recursion call:

int findMinimumValue(struct tnode* node)
{
    int min=node->data;

    if(node->lchild==NULL)
    {
        return min;
    }
    else
    {
        // you need the return here or you're never returning 
        // anything in this branch
        return findMinimumValue(node->lchild);
    }
}

for that matter not really much need for the variable as it is, what about:

int findMinimumValue(struct tnode* node)
{
    if (node->lchild == NULL)
        return node->data;
    else
        return findMinimumValue(node->lchild);
}

oh, and just as a mention: I would consider using the non-recursive version of this instead; it's also pretty simple:

int findMinimumValue(struct tnode* node)
{
    while (node->lchild != NULL)
        node = node->lchild;

    return node->data;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消