union-find

84 阅读1分钟

Quick-find

image.png

Quick-union

image.png

Weighted quick-union

Rather than arbitrarily connecting the second tree to the first for union(), we keep track of the size of each tree and always connect the smaller tree to the larger.

image.png

image.png

Weighted quick union with path compression

image.png

Ideally, we would like every node to link directly to the root of its tree, but

we do not want to pay the price of changing a large number of links, as we

did in the quick-find algorithm. We can approach the ideal simply by

making all the nodes that we do examine directly link to the root.