Reputation: 5
I need some help on how to find the (sorted) position of a given value in a Binary Search Tree better than I already did (if possible).
I have another method that searches for the i-th element of the tree and returns the node. So basically I solved the problem by searching through the tree until I find the given value or the node's data is bigger than the value I am searching for.
Our teacher gave us the algorithm on how to find the i-th element by knowing how many elements are there in that subtree. That is why I am wondering if my problem can be done in less steps?
Thanks in advance!
This is the not so optimal solution:
template <class T>
int BST<T>::Rang(const T& x) {
int meret = root->size; //meret = size of the whole
//tree
Node<T>* temp = i_th_Node_rec(1, root);
int i = 1;
while (temp && i <= meret && x != temp->data && x < temp->data) {
++i;
temp = i_th_Node_rec(i, root);
}
return (i < meret) ? i : -1;
}
Upvotes: 0
Views: 1377
Reputation: 66451
It's very similar to how you locate the i:th node, but "in reverse".
Upvotes: 3