LeetCode 261 Graph Valid Tree - Solution

The core idea

For a valid tree: edges = n - 1, and all nodes are connected.

First, quick check: if edges ≠ n - 1, return false.

Then DFS/BFS from node 0. Count how many nodes you visit. If you visit all n nodes, it's a valid tree.

Why no separate cycle check? With exactly n-1 edges, if all nodes are connected, there cannot be a cycle (a cycle would require at least n edges to connect n nodes).