且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

分而治之算法树木

更新时间:2022-11-29 11:44:16

我想你可以用这样的算​​法做到这一点:

I think you could do it with an algorithm like this:

开始在根(如果树没有根,选择的任何节点)。
在每个步骤中,尽量降入具有最大的子树(节点下方它是最大的数)的子节点。
如果这样做,会使高于大于N / 2节点的数量,停止,否则继续这个孩子。

Start in the root (if the tree isn't rooted, pick any node).
In each step, try to descend into the child node that has the largest subtree (the number of nodes "below" it is the biggest).
If doing that would make the number of nodes "above" bigger than n/2, stop, otherwise continue with that child.

这个算法应该是O(log n)的,如果树是合理的平衡,我们有pcomputed每个节点的子树$ P $大小。如果这些条件之一不适用,这将是为O(n)。

This algorithm should be O(log n) if the tree is reasonably balanced and we have sizes of subtrees precomputed for each node. If one of those conditions doesn't apply, it would be O(n).