AutomEng
AutomEng

Reputation: 455

C# BST search method implementation, "Not all code paths return a value"

I am trying to implement a search method for a Binary Search Tree in C#. I chose to do it recursively rather than iteratively. The method basically takes the key (in this case "item") and the root node of the tree (or subtree) to start checking against. There is definitely a problem in the else if clauses but I cannot pinpoint it. Any help will be appreciated. Cheers!

public bool Search(int item, TreeNode searchRoot){

        if (searchRoot != null) {
            if (item == searchRoot.GetItem ()) {
                return true;
            } else if (item < searchRoot.GetItem ()) {
                Search (item, searchRoot.GetLeftNode ());
            } else if (item > searchRoot.GetItem ()) {
                Search (item, searchRoot.GetRightNode ());
            }
        } else {
            return false;
        }
    }

Upvotes: 0

Views: 71

Answers (2)

Omidam81
Omidam81

Reputation: 1917

public bool Search(int item, TreeNode searchRoot){

    if (searchRoot != null) {
        if (item == searchRoot.GetItem ()) {
            return true;
        } else if (item < searchRoot.GetItem ()) {
            return Search (item, searchRoot.GetLeftNode ());
        } else if (item > searchRoot.GetItem ()) {
            return Search (item, searchRoot.GetRightNode ());
        }
    } else {
        return false;
    }
}

Upvotes: 1

Arghya C
Arghya C

Reputation: 10068

This should fix your code. You need to add return for recursive calls. And, return something for all conditions in first if. Changing the last else-if to else should work fine.

public bool Search(int item, TreeNode searchRoot)
{
    if (searchRoot != null)
    {
        if (item == searchRoot.GetItem ())
            return true;
        else if (item < searchRoot.GetItem ())
            return Search (item, searchRoot.GetLeftNode ());
        else 
            return Search (item, searchRoot.GetRightNode ());
    }
    else
        return false;
}

Upvotes: 1

Related Questions