Path compression makes every node on the find path point directly to the root:
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
After calling find(x), every node from to the root now points directly to the root. Future finds on these nodes are .
Example: chain (4 is root). After find(1):
- (root)
The tree flattens completely. You see the power of path compression—even if trees get tall temporarily, find operations flatten them.