简体   繁体   中英

An algorithm to find all nodes greater than some value X in a binary max heap

Here is what I have so far.

We can use recursive algorithm that starts at the root of the heap (since the root is the max number. We will then check to see if our X (what we're looking for) is greater than our root. If X is greater than the root we stop. If not, we print the root and then we check it's left child and right child. And so on...

Is this a good algorithm? Also will the worse case time complexity of my algorithm be O(N) in which N is the # of nodes in the heap.

This algorithm is good. In fact, its optimal in terms of time complexity as it visits at most 3 * k nodes, where k is the number of nodes that satisfy the given condition (it is the case because the node is visited only if it satisfies the condition or its parent does).

Yes, it's O(N) in the worst case. But you cannot do better because you might need to print all the nodes in the heap.

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