简单更详细的实现

为了有效地处理循环检测,我们将每个节点视为树的一部分。添加边时,我们检查它的两个组件节点是否是不同树的一部分。最初,每个节点组成一个单节点树。

algorithm kruskalMST'(G: a graph)
    sort G's edges by their value
    MST = a forest of trees, initially each tree is a node in the graph
    for each edge e in G:
        if the root of the tree that e.first belongs to is not the same 
        as the root of the tree that e.second belongs to:
            connect one of the roots to the other, thus merging two trees
    
    return MST, which now a single-tree forest