繁体   English   中英

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

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

我知道如果树是平衡的,在 BST 中搜索节点的最坏情况时间复杂度是 O(logn)。 但是如何在 BST 中搜索数字 t 的下限呢?

因为在上面的场景中,我们不只是搜索一个精确的节点,而是一个与 t 接近或相同但不大于 t 的节点。 涉及许多标准。 那么它仍然是 O(logn) 最坏的情况吗? (树是平衡的)

下面是我的代码,我正在努力寻找最坏情况的时间复杂度:

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;
}

谢谢。

时间复杂度仍然是 O(log𝑛),因为从根到叶只有一条路径。 唯一的变化是递归调用产生的值可能不会保留,而是将当前节点的值用作返回值(参见代码中的最后一条语句)。 但这是一个不会影响整体复杂性的持续操作。

暂无
暂无

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

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