[英]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... 我们可以使用从堆的根开始的递归算法(因为根是最大数。然后,我们将检查X是否大于我们的根。如果X大于根目录我们停止了,如果没有,我们打印根目录,然后检查它是左子节点还是右子节点,依此类推...
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. 我算法的最坏情况下的时间复杂度也将是O(N),其中N是堆中节点的数量。
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). 实际上,它在访问最多3 * k
节点时在时间复杂度方面是最优的,其中k
是满足给定条件的节点数(之所以如此,是因为只有满足条件或满足条件的节点才被访问父母)。
Yes, it's O(N)
in the worst case. 是的,最坏的情况是O(N)
。 But you cannot do better because you might need to print all the nodes in the heap. 但是您不能做得更好,因为您可能需要打印堆中的所有节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.