Two conditions to check:
Exactly edges (necessary for any tree)
No cycles (every union should succeed)
def validTree(n, edges):
if len(edges) != n - 1:
return False
uf = UnionFind(n)
for u, v in edges:
if not uf.union(u, v):
return False # cycle detected
return True
if you have exactly edges and no cycles, the graph must be connected. Why? An acyclic graph with nodes and edges has exactly one component (any more components would require fewer edges).
Time: . Space: .