简体   繁体   English

在给定的平衡二分搜索树中找到最小(或最大)的k个元素

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

Given a balanced binary search tree with integer nodes, I need to write an algorithm to find the smallest k elements and store them in a linked list or array. 给定一个带有整数节点的平衡二进制搜索树,我需要编写一种算法来查找最小的k个元素并将它们存储在链接列表或数组中。 The tricky part is, it is required such algorithm runs in O(k+log(n)), where n is the number of elements in the tree. 棘手的部分是,要求这种算法在O(k + log(n))中运行,其中n是树中元素的数量。 I only have an algorithm that runs O(k*log(n)), which uses the rank function. 我只有一个运行O(k * log(n))的算法,该算法使用了rank函数。 So my question is how to achieve the required performance? 所以我的问题是如何达到所需的性能?

I've written a code doing such algorithm but I don't know if it is running at O(k+log(n)): 我已经编写了执行这种算法的代码,但不知道它是否以O(k + log(n))运行:

(The size function is the number of nodes with the given subtree.) (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);
    }
}

Just have to to a inorder traversal and stop when you have gone through k nodes. 只需进行有序遍历并在遍历k个节点时停止。 this would run in O(k+log(n)) time. 这将在O(k + log(n))时间中运行。

code: 码:

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