Reputation: 455
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
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
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