IBM Interview Question
Software Engineer / DevelopersIf vmin < min inside tree and vmax > max in tree, you have to print them all => O(n)
But, vmax - vmin = constant (does not depend on the input size) => O(log n + ct) = O(log n).
Therefore, I don't think it is possible to print all values greater than vmin and lower than vmax in O(log n).
But if the nodes are consecutive numbers, you can find the start node and the end node in O(log n) and print the inner values in O(vmax - vmin) => O(log n + vmax - vmin).
pseudo code:
findrange(bst,min,max){
if (bst==null) return ;
if(min<= bst->data <= max) {
findrange(bst->left,min,max);
print bst->data;
findrange(bst->right,min,max);
}
elseif (bst->data <min)
findrange(bst->right,min,max);
elseif (bst->data <max)
findrange(bst->left,min,max);
else
return;
}
just add a condition
- Anonymous August 25, 2010(if(root->value)>vmin && root->value<vmax){
inorder(root->left);
print(root->value);
inorder(root->right);
}