Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

algorithm

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.

like image 244
name Avatar asked Oct 19 '25 13:10

name


1 Answers

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.

like image 140
kraskevich Avatar answered Oct 22 '25 02:10

kraskevich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!