Data Structures19 sections · 729 units
Open in Course

Valid Tree Solution

Check edges and connectivity

Two conditions to check:

1.1. Exactly n1n - 1 edges (necessary for any tree)

2.2. No cycles (every union should succeed)

function validTree(n, edges):
    if edges.length != n - 1:
        return false

    uf = new UnionFind(n)
    for each (u, v) in edges:
        if not uf.union(u, v):
            return false  // cycle detected

    return true

if you have exactly n1n-1 edges and no cycles, the graph must be connected. Why? An acyclic graph with nn nodes and n1n-1 edges has exactly one component (any more components would require fewer edges).

Time: O(nα(n))O(n)O(n \cdot \alpha(n)) \approx O(n). Space: O(n)O(n).