Graph Valid Tree
Return whether the undirected graph on n nodes labeled 0..n-1 is a tree: connected and acyclic.
Example 1
n = 4
edges = [[0,1],[1,2],[1,3]]trueExplanation
Four nodes connect through three edges without a cycle.
Example 2
n = 3
edges = [[0,1],[1,2],[2,0]]falseExplanation
Three edges form a cycle, violating the tree requirement.
Example 3
n = 3
edges = [[0,1]]falseExplanation
Node 2 is disconnected from nodes 0 and 1.
Example 4
n = 1
edges = []trueExplanation
A single node is connected to itself and has no cycle, so it is a tree.
Constraints
- 1 <= n <= 2000
- Edges are distinct valid unordered pairs without self-loops
Function contract
validTreeArguments: json, jsonSolutionRuns on your device
Loading draft…
Run: 3 examples; Submit: 35 cases, on your device.
4[[0,1],[1,2],[1,3]]