Ridimz said:
I have implemented a binary search tree and am interested in displaying all
keys less than a certain value. I understand how to approach this task if
the searchValue is equal to root.key(). Otherwise I'm lost. Any suggestions
or examples would be greatly appreciated
What do you know about a node in a BST and it's relationship to
the subnodes.
You know that in the left subtree of that node there are only nodes with
values less then the current nodes value. In the right subtree there
are only nodes with values greater then the current node.
So if you start at the root. Look at the roots value.
If it is greater then the value you use for the limit,
then you know imediatly that all nodes in the right subtree are
also greater then your limit. None of that nodes can be in your
output set. What about the nodes in the left subtree? Well.
They clearly are less then the roots node, but are they also less
then your limit? Some may be, some may not be. So you need to investigate
further.
What happens if a you encounter a tree node, which has a value less then your
limit. Well. You know imediatly that all nodes in the left subtree are clearly
less then your limit and belong to the output set. What about the nodes in
the right subtree? Some of them might be less then your limit, some may not.
Further investigation is neccessarry.
From all of this, you could come up with a strategy as follows (pseudocode)
SearchLessThenLimit( node, limit )
{
if( node->value > limit ) {
// right subtree is unimportant, can be ignored
// as can this node
SearchLessThenLimit( node->left, limit )
}
else {
if( node->value < limit ) {
output( node );
}
OutputAllIn( node->left );
SearchLessThenLimit( node->right, limit )
}
}