Re > Binary Search Tree Search Function

hi guys,

I've been recently implementing my own BST, and I've came to a problem which is giving me quite a bit of headache.

I've written a search function to return a true/false whether a item exist in the BST, however now I wish to write a function that returns me the object instead.

Would appreciate any help possible, below is the code I've came out with for searching the bst.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  template <class elemType>
bool bSearchTreeType<elemType>::search
	(const elemType& searchItem) const
{
	nodeType<elemType> *current;
	bool found = false;
	if (root == NULL)
		cout << "Cannot search an empty tree." << endl;
	else
	{
		current = root;
		while (current != NULL && !found)
		{
			if (current->info == searchItem)
				found = true;
			else if (current->info > searchItem)
				current = current->lLink;
			else
				current = current->rLink;
		}//end while
	}//end else
	return found;
}
You could add a variable of type elemType that holds the found object and return it.
hi,

thanks for the reply, but however it doesn't seem to be working, I've tried writing a additional function to try to return the object but it doesn't seem to be working.

When you find the item in the while loop, just break out of the loop. That way when you exit the loop, "current" will be the item you're looking for, or NULL. You don't need "found" at all.

And notice that once you've got the "search" method working, you don't even need the "does it exist" method. Just check the return value from "search" to whether it's NULL.
Topic archived. No new replies allowed.