簡體   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