Representing the output of the Kruskal's minimal spanning tree algorithm as a tree data structure

75 Views Asked by At

I tried to implement Kruskal's minimal spanning tree algorithm and I found that the output is essentially a set of the edges... The output is not a tree at all. In my opinion, a tree can be represented by a parents array, and each node associates a key which is its parent. For a tree we need to know which node is its root at least I think. But the output of Kruskal's algorithm are just edges. How to fill this gap?

1

There are 1 best solutions below

1
On

The output of Kruskal's algorithm is a tree: it is an acyclic connected graph.

If you want to represent it by a "parents array", this can be done by a depth-first search through the tree. (An anything-first search will do, really; the point of having a tree is that there's only one way to traverse it.) Pick an arbitrary vertex to be the root of the tree. As you explore the rest of the tree by DFS, whenever you visit a vertex $v$, set $v$'s parent to be whichever vertex you visited it from.

It may be simpler to use Prim's algorithm instead. Prim's algorithm starts with a single vertex, and extends it to a larger and larger tree until the tree is a spanning tree. You can create the "parents array" representation of the tree as you go: whenever you identify a new cheapest edge $vw$, where $w$ is a vertex not previously part of the tree, set $w$'s parent to be $v$.