简体   繁体   English

在 BST 中查找数字的下限的最坏情况时间复杂度

[英]worst case time complexity of finding the floor of a number in a BST

I know that the worst case time complexity of searching a node in a BST is O(logn) if the tree is balanced.我知道如果树是平衡的,在 BST 中搜索节点的最坏情况时间复杂度是 O(logn)。 But what about searching for a floor of a number t in a BST?但是如何在 BST 中搜索数字 t 的下限呢?

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.因为在上面的场景中,我们不只是搜索一个精确的节点,而是一个与 t 接近或相同但不大于 t 的节点。 there are many criterias involved.涉及许多标准。 So would it still be O(logn) worst case?那么它仍然是 O(logn) 最坏的情况吗? (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.时间复杂度仍然是 O(log𝑛),因为从根到叶只有一条路径。 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.但这是一个不会影响整体复杂性的持续操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM