Reputation: 75
For a BST, I want to find the nodes' values in [a,b] form largerest value to smallest one. The simplest way I can think is as follows:
void printRange(BSTNode<Key,E>* root,int lowValue,int highValue) const
{
if(root==NULL) return;
printRange(root->right(),lowValue,highValue);
if(root->key()>=lowValue&&root->key()<=highValue)
cout<<root->key()<<" ";
printRange(root->left(),lowValue,highValue);
}
But I want to know whether there is a way to print out these values with less nodes visited?
Upvotes: 0
Views: 1973
Reputation: 808
The answer to this question, is psuedo code, should have been this:
void printRange(int lower, int upper, BSTNode * node){
if (node == NULL) return
if (node->key <= upper) printRange(lower, upper, node->right);
if (node->key >= lower && node->key <= upper) printf("%d",node->value);
if (node->key >= lower) printRange(lower, upper, node->left);
}
Upvotes: 1
Reputation: 43245
You are visiting all the nodes of the BST , irrespective of whether they lie in the range or not. And printing only the required values. A more refined algorithm would be :
Do inorder traversal of the BST.
Start from the root.
Process left subtree for inorder traversal only if the root of left subtree is smaller than 'lowValue'
Process right subtree only if root of right subtree is greater than 'highValue'
Else just return from the function.
This way you do a filtered inorder traversal,visiting only the required part of your BST .
Upvotes: 1