1

My code is for searching a Binary Tree for the same value given.

To me it is returning a value.

Any ideas/help?

public Boolean ContainsValue (Node<T> tree, int value)
{
    if (tree == null)
        return false;

    if (tree.Data.Equals(value))
        return true;

    if (value.CompareTo(tree.Data) < 0)
        return ContainsValue(tree.Left, value);

    if (value.CompareTo(tree.Data) > 0)
        return ContainsValue(tree.Right, value);
}

EDIT: Thanks I realised what I did wrong once you all mentioned the problem. (I now feel very silly)

1
  • What if none of your if statement won't work? Your method does not return anything. Commented Jan 18, 2014 at 17:00

2 Answers 2

4

You need default (unconditional) return for case when none of conditions was satisfied:

public Boolean ContainsValue (Node<T> tree, int value)
{
    if (tree == null)
        return false;

    if (tree.Data.Equals(value))
        return true;

    if (value.CompareTo(tree.Data) < 0)
        return ContainsValue(tree.Left, value);

    if (value.CompareTo(tree.Data) > 0)
        return ContainsValue(tree.Right, value);

    // here
    // return some_value;
    // or throw exception
}

I think your code should look like:

public bool ContainsValue (Node<T> tree, int value)
{
    if (tree == null)
        return false;

    if (tree.Data.Equals(value))
        return true;

    if (value.CompareTo(tree.Data) < 0)
        return ContainsValue(tree.Left, value);

    // thus you already verified case when value is less or equal to data
    // you don't need if condition here
    return ContainsValue(tree.Right, value);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need a default return value for the method. Your only return values are in IF statements, so the compiler will complain, even if we as humans can see that at least one IF statement will execute.

Comments

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.