Recall that union-find is implemented as an inverted tree, where for each set S = {v 1 , v 2 , ..., v n }, you have v n - 1 edges, which ultimately have the same root (or receiver).
Now, when you add an edge (v i , v j ) to this tree, add another edge (using the new attribute) (v j , v i ). And when you delete the node, also remove this attribute.
Please note that the new edge is separate from the old. You use it only when printing all elements in a set. And change it when the original edge changes in the original algorithm.
Note that this attribute is actually a list of nodes, but the total number of elements in all lists is still n - 1 combined.
This will give you a second tree, but not upside down. Now, using the root and traversing the tree (using BFS or DFS ), you can print all the elements.
amit
source share