簡體   English   中英

在給定的平衡二分搜索樹中找到最小(或最大)的k個元素

[英]Finding smallest (or largest) k elements in a given balanced binary search tree

給定一個帶有整數節點的平衡二進制搜索樹,我需要編寫一種算法來查找最小的k個元素並將它們存儲在鏈接列表或數組中。 棘手的部分是,要求這種算法在O(k + log(n))中運行,其中n是樹中元素的數量。 我只有一個運行O(k * log(n))的算法,該算法使用了rank函數。 所以我的問題是如何達到所需的性能?

我已經編寫了執行這種算法的代碼,但不知道它是否以O(k + log(n))運行:

(size函數是具有給定子樹的節點數。)

// find k smallest elements in the tree
public Iterable<Key> kSmallest(int k) {
    LinkedList<Key> keys = new LinkedList<Key>();
    kSmallest(k, root, keys);
    return keys;
}

// find k smallest elements in the subtree given by node and add them to keys
private void kSmallest(int k, Node node, LinkedList<Key> keys) {
    if (k <= 0 || node == null) return;
    if (node.left != null) {
        if (size(node.left) >= k) kSmallest(k, node.left, keys);
        else {
            keys.add(node.key);
            kSmallest(k - 1, node.left, keys);
            kSmallest(k - 1 - size(node.left), node.right, keys);
        }
    }
    else {
        keys.add(node.key);
        kSmallest(k - 1, node.right, keys);
    }
}

只需進行有序遍歷並在遍歷k個節點時停止。 這將在O(k + log(n))時間中運行。

碼:

int k = nodesRequired;
int A[] = new int[k];
int number_of_nodes=0;
void traverse_tree(tree *l){
    if (number_of_nodes<k) {
        traverse_tree(l->left);
        process_item(l->item);
        traverse_tree(l->right);
    }
 }

 void process_item(item){
     A.push(item);
     ++number_of_nodes;
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM