LeetCode 261 Graph Valid Tree - Example and Complexity Analysis

Walkthrough and analysis

Check n=5, edges=[[0,1],[0,2],[0,3],[1,4]].

Edge count: 4 = 5 - 1. ✓

Build adjacency list: {0:[1,2,3], 1:[0,4], 2:[0], 3:[0], 4:[1]}.

DFS from 0. Visit: 0, 1, 4, 2, 3. Count = 5 = n. ✓

Return true.

For n=5, edges=[[0,1],[1,2],[2,3],[1,3],[1,4]]: 5 edges ≠ 4. Return false immediately.

Build adjacency: O(E)O(E). DFS: O(V+E)O(V + E). Total: O(V+E)O(V + E) time and space.