0

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);
}
5
  • What language is this? (Please tag the question appropriately.) Have you attempted to debug this? Commented Aug 21, 2011 at 11:01
  • 2
    If you turned up your compiler's warning level, you would find the problem immediately. Commented Aug 21, 2011 at 11:04
  • I did not get any error while I was running and compiling the code. Commented Aug 21, 2011 at 11:06
  • Tree created is fine. i am able to traverse the tree properly. But I dont know why the value is comin out to be 0. Below is the way i have made a call to the function. cout<<findMinimumValue(root) Commented Aug 21, 2011 at 11:08
  • Yes, exactly. You should set your compiler to use a higher warning level. (In GCC, you can do -Wall -Wextra; in VS you can use /W3 or /W4.) Commented Aug 21, 2011 at 11:09

1 Answer 1

6

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

bleah, getting too late to write answers had to edit twice because somehow I went from thinking "no return in this branch" to typing "min =". in two places.
Thanks. Now it worked. It was a stupid mistake from my side. I have many problems in recursion. can you please suggest some tutorial link ets to improve the concept.
:) I've been there, no worries. recursion can be hard. as for a tutorial, a quick google turned this one up, it seemed pretty cool: erwnerve.tripod.com/prog/recursion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.