I know that the worst case time complexity of searching a node in a BST is O(logn) if the tree is balanced. But what about searching for a floor of a number t in a BST?
because in the above scenario, we are not just searching for an exact node, but a node that is close or the same as t but not greater than t. there are many criterias involved. So would it still be O(logn) worst case? (tree is balanced)
below is my code and I'm struggling to find the worst case time complexity for this:
struct Node {
int data;
Node *left, *right;
};
int floor(Node* root, int key)
{
if (!root)
return INT_MAX;
/* If root->data is equal to key */
if (root->data == key)
return root->data;
/* If root->data is greater than the key */
if (root->data > key)
return floor(root->left, key);
/* Else, the floor may lie in right subtree
or may be equal to the root*/
int floorValue = floor(root->right, key);
return (floorValue <= key) ? floorValue : root->data;
}
Thanks.
The time complexity is still O(log𝑛), because there is only one path that is followed from the root to a leaf. The only change is that the value that comes out of the recursive call is potentially not retained, but instead the current node's value is used as return value (cf. the last statement in your code). But this is a constant operation that does not impact the overall complexity.