Graph Valid Tree
Medium · Graphs
On LeetCode, Graph Valid Tree needs LeetCode Premium (checked October 2026). Here it is free: run and submit in Python, JavaScript, Java or C++ with a free account.
Jump to codeGiven n ≥ 1 vertices labeled 0 through n−1 and undirected edges without self-loops or duplicate edges, decide whether the graph is one tree.
Examples
Example 1
n = 5 edges = [[0,1],[0,2],[0,3],[1,4]]
Output: true
Example 2
n = 5 edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
Output: false
Constraints
- 1 <= n <= 100
- 0 <= edges.length <= n * (n - 1) / 2
Need a hint?
A tree is connected and has exactly n−1 edges.
Real graph interview questions
Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.
- Count Islands in a Grid and Track the Count as Land Cells Are AddedGoogle
- Order Tasks with Dependencies Using a Deterministic Topological SortOpenAI
- Snake Game: Minimum Moves to Reach the AppleJane Street
Solution approach
Reject any edge count other than n−1. Build adjacency lists and traverse from vertex 0, marking each vertex once. Accept only if all n vertices are reached. With n−1 edges, connectivity also rules out cycles.
Complexity
O(n + E) time and space.
Python reference solution
def validTree(n, edges):
if len(edges) != n - 1:
return False
neighbors = [[] for _ in range(n)]
for a, b in edges:
neighbors[a].append(b)
neighbors[b].append(a)
seen, stack = {0}, [0]
while stack:
for neighbor in neighbors[stack.pop()]:
if neighbor not in seen:
seen.add(neighbor)
stack.append(neighbor)
return len(seen) == n
JavaScript solution
function validTree(n, edges) {
if (edges.length !== n - 1) return false;
const neighbors = Array.from({length: n}, () => []);
for (const [a, b] of edges) { neighbors[a].push(b); neighbors[b].push(a); }
const seen = Array(n).fill(false);
let count = 0;
for (let start = 0; start < n; start++) {
if (seen[start]) continue;
count++; seen[start] = true;
const stack = [start];
while (stack.length) {
for (const next of neighbors[stack.pop()]) {
if (!seen[next]) { seen[next] = true; stack.push(next); }
}
}
}
return count === 1;
}
Java solution
import java.util.*;
class Solution {
public boolean validTree(int n, int[][] edges) {
if (edges.length != n - 1) return false;
List<List<Integer>> neighbors = new ArrayList<>();
for (int i = 0; i < n; i++) neighbors.add(new ArrayList<>());
for (int[] edge : edges) { neighbors.get(edge[0]).add(edge[1]); neighbors.get(edge[1]).add(edge[0]); }
boolean[] seen = new boolean[n];
int count = 0;
for (int start = 0; start < n; start++) {
if (seen[start]) continue;
count++; seen[start] = true;
Deque<Integer> stack = new ArrayDeque<>();
stack.push(start);
while (!stack.isEmpty()) {
for (int next : neighbors.get(stack.pop())) {
if (!seen[next]) { seen[next] = true; stack.push(next); }
}
}
}
return count == 1;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool validTree(int n, vector<vector<int>> &edges) {
if ((int)edges.size() != n - 1) return false;
vector<vector<int>> neighbors(n);
for (auto& edge : edges) { neighbors[edge[0]].push_back(edge[1]); neighbors[edge[1]].push_back(edge[0]); }
vector<bool> seen(n);
int count = 0;
for (int start = 0; start < n; start++) {
if (seen[start]) continue;
count++; seen[start] = true;
vector<int> pending{start};
while (!pending.empty()) {
int node = pending.back(); pending.pop_back();
for (int next : neighbors[node]) {
if (!seen[next]) { seen[next] = true; pending.push_back(next); }
}
}
}
return count == 1;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 7 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
5,
[
[
0,
1
],
[
0,
2
],
[
0,
3
],
[
1,
4
]
]
]true
[
5,
[
[
0,
1
],
[
1,
2
],
[
2,
3
],
[
1,
3
],
[
1,
4
]
]
]false
[ 1, [] ]
true
[
4,
[
[
0,
1
],
[
1,
2
],
[
2,
3
]
]
]true
[
4,
[
[
0,
1
],
[
2,
3
]
]
]false
Drafts are saved per language in this browser when storage is available.