Graph Valid Tree
Question (LC.261)
Given n nodes (label in [0, n-1]) and list of undirected edges, validate the given graph is a tree.
Assume that no duplicate edges will appear in edges.
Example
Input: n = 5, edges = [[0, 1], [0, 2], [0, 3], [1, 4]]
Graph: ->1->4
0->2
->3
Output: true it is a valid treeInput: n = 5, edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]
Graph: 0
|
1
/ \ \
2 | 4
\ /
3
Output: A tree cannot contain cycles. False.Analysis
What differentiates a tree from a graph? Here are the things we want to check:
The graph is acyclic
The graph is connected
Each tree has |nodes| - 1 edges. If the graph does not have cycle, then it is a valid tree.
DFS
This should be the most intuitive approach. We want to see if the component is connected and without any cycle.
Main function
Build (Directed) Graph
DFS and Cycle Detection
BFS
If the graph is neighbor under connected nor over connected, then we can try to explore the whole graph from a node. If we explored all the nodes on this graph (connected), then it is acyclic. Otherwise, it has cycles and it's not connected.
Main function
BFS Explore
Note 1: We have to add visited after offer bucause some elements can still be in queue but not processed yet. We don't want to visit the same node again. Note 2: Stay away from Integer and other wrappers if you can since they are all immutable.
Union Find
The solution can be very elegant using this approach. The idea to find two vertices (v1, v2) first. If they don't belong to the same set (no cycle), then union them.
References
Last updated