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 trueif the edges of the given graph make up a valid tree, andfalseotherwise.
A valid tree must have precisely n - 1 edges and it must be fully connected (all nodes are reachable from starting point).
Hint 2How to detect cycles using DFS?▼
When traversing from node to a neighbor, if the neighbor is already visited AND it is not the parent node that brought you here, you've found a cycle!
Optimal Approach — Depth First Search (DFS)
O(N + E) Time
🔍
Traverse Graph using DFS & Count Nodes visited
Time O(N + E)Space O(N + E)
We can utilize depth-first search to traverse our given graph. While exploring, we track visited nodes and the parent of the current node.
1Quick check: A tree with n nodes must have exactly n - 1 edges.
2Build an adjacency list representation of the graph.
3Run DFS from node 0. Passing down its parent to avoid traversing backwards.
4If a visited node is encountered that is not the parent, a cycle exists. Return false.
5After DFS finishes, verify len(visited) == n to verify there are no disconnected components.
DFS Graph Traversal
📋 Call Stack
— empty —
✓ Visited Set
∅
🔗 Adjacency List parent → [children]
—
READY—
Press ▶ or step forward to begin.
✓
✕
—
Executing Code
defvalidTree(n, edges):
iflen(edges) != n - 1: return False
adj = [[] for _ inrange(n)]
for u, v in edges: adj[u].append(v); adj[v].append(u)
visited = set()
defdfs(node, parent):
if node in visited: return False
visited.add(node)
for nxt in adj[node]:
if nxt != parent:
if notdfs(nxt, node): return False
return True
returndfs(0, -1) andlen(visited) == n
Alternative Approach — Breadth First Search (BFS)
O(N + E) Time
🌊
Layer-by-Layer Traversal using Queue
Time O(N + E)Space O(N + E)
Similar to DFS, we can also use **Breadth First Search (BFS)** to identify a valid tree. Instead of going as deep as possible, BFS explores node connections layer-by-layer.
BFS Graph Traversal
🔄 Queue
— empty —
✓ Visited Set
∅
🔗 Adjacency List parent → [children]
—
READY—
Press ▶ or step forward to begin.
✓
✕
—
Executing Code
from collections import deque
defvalidTreeBFS(n, edges):
iflen(edges) != n - 1: return False
adj = [[] for _ inrange(n)]
for u, v in edges: adj[u].append(v); adj[v].append(u)
Discussion
…