Graph Valid Tree

Medium
Union Find

You have a graph of n nodes labeled from 0 to n - 1. You are given an integer n and a list of edges where edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the graph.

Return true if the edges of the given graph make up a valid tree, and false otherwise.

Tree Properties:

  1. A tree with n nodes has exactly n-1 edges
  2. A tree is connected (all nodes reachable from any node)
  3. A tree has no cycles

Union Find Approach:

  1. Check if number of edges equals n-1 (necessary condition)
  2. Process each edge with Union Find
  3. If find(a) == find(b) before union, there's a cycle - not a tree!
  4. After all edges, check if all nodes are in the same component

Key Insight: A valid tree is a connected graph with no cycles. Union Find detects cycles and connectivity simultaneously.

Example 1

Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
Output: true
Explanation: The graph is connected with 4 edges (n-1) and no cycles. It is a valid tree.

Example 2

Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
Output: false
Explanation: There is a cycle: 1-2-3-1. Trees cannot have cycles.

Example 3

Input: n = 5, edges = [[0,1],[2,3]]
Output: false
Explanation: The graph is not connected. Node 4 is isolated, and {0,1} and {2,3} are separate components.

Constraints

  • 1 <= n <= 2000
  • 0 <= edges.length <= 5000
  • edges[i].length == 2
  • 0 <= ai, bi < n
  • ai != bi
  • There are no self-loops or repeated edges.
Show Hints (4)
Hint 1: A tree with n nodes must have exactly n-1 edges. Is this sufficient to guarantee a valid tree?
Hint 2: If you have n-1 edges but the graph is disconnected, can it be a tree?
Hint 3: Use Union Find to process edges. What does it mean if find(a) == find(b) before we union them?
Hint 4: After processing all edges, how many connected components should a valid tree have?
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?