简体   繁体   中英

How to find the top k largest elements more efficiently

How to find the k largest elements in a binary search tree faster than in O(logN + k)

I implemented the algorithm with the said asymptotics, but how to make it faster?

Extend your tree data structure with the following:

  • Make your tree threaded , ie add a parent reference to each node.

  • Maintain a reference to the node that has the maximum value (the "rightmost" node). Keep it up to date as nodes are added/removed.

With that information you can avoid the first descent from the root to the rightmost node, and start collecting values immediately. If the binary tree is well balanced, then the rightmost node will be on (or near) the bottom layer of the tree. Then the walk along the tree in reversed inorder sequence -- for finding the greatest valued nodes -- will make you traverse a number of edges that is O().

Alternative structures, such as B+ tree and skip list can also provide O() access to the greatest values they store.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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