FAANGPrep Sprint
Graph Valid Tree
Determine if a set of edges forms a valid tree.
Examples
No cycles, fully connected.
Cycle exists: 1-2-3-1.
Problem Understanding
A Tree is a special type of Graph that satisfies two conditions:
- Fully Connected: You can reach any node from any other node.
- Acyclic: It contains no cycles.
Alternatively: A graph with N nodes is a tree if it is fully connected and has exactly N - 1 edges.
Algorithm Strategy (DFS)
We can use DFS to check for cycles and connectivity.
- Build Graph: Create adjacency list.
- DFS from Node 0: Keep track of
visitedset to detect cycles.- Since the graph is undirected,
A-BmeansBis a neighbor ofA. We must not count the immediateparentas a cycle. - Pass
parentto the DFS call:dfs(node, parent). - If
neighbor != parentandneighboris visited -> Cycle Detected! Return false.
- Since the graph is undirected,
- Check Connectivity: After DFS,
visited.size()must equaln. If not, the graph is disconnected.
Visualization
GREEN = EDGES DFS WALKED · RED = THE EDGE THAT CLOSES A CYCLE
BUILD LIST
Edges
4 (n − 1 = 4)
Visited
0 / 5
Valid tree
—
call stack
No dfs running
Build the adjacency list: 5 lists, each of the 4 edges added to both ends
Next
Call dfs(0, -1): start at node 0, which has no parent
edges
n
DFS from node 0 carries the node it came from. The edge back to that parent is skipped; any other edge that leads to a node already visited closes a cycle, and it turns red. Green edges are the ones DFS walked down. If DFS finishes without a cycle, the last check looks for a node it never reached — try the Two pieces preset.
