Question about choosing the root node - can we end up with two root nodes for the same province?
103

Let's say we have very simple example, three cities: 1, 2, 3. Those 3 cities are connected together, like 1 - 2 - 3. Now we have to do unions, so we can for example do:

unionSet(1, 2);
unionSet(2, 3);

Everything fine so far, root node will be correctly written for all of them (1).

Now consider if we did unions like that:

unionSet(1, 2);
unionSet(3, 2);

That would result in two root nodes, (1) and (3). I think the union function has a flaw. It requires particular order of elements. Am I right?

I'm using unionSet function from the example.

   void unionSet(int x, int y) {
        int rootX = find(x);
        int rootY = find(y);
        if (rootX != rootY) {
            root[rootY] = rootX;
        }
    }
Comments (2)