261. Graph Valid Tree
Medium NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- Graphs
- Time
- O((n + e) * alpha(n))
- Space
- O(n)
Standard Solution (C++)
SummaryDecide whether n nodes connected by the given undirected edges form a valid tree: fully connected with no cycles.
Approach
Union-Find with edge-count check. A graph on n nodes is a tree exactly when it has n-1 edges and is fully connected (equivalently, acyclic).
- If the number of edges is not n-1, it cannot be a tree.
- Otherwise union every edge; if any edge connects two nodes already in the same set, there is a cycle and it is not a tree.
class Solution {
vector<int> parent;
int find(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
public:
bool validTree(int n, vector<vector<int>>& edges) {
if ((int)edges.size() != n - 1) return false;
parent.resize(n);
for (int i = 0; i < n; ++i) parent[i] = i;
for (auto& e : edges) {
int a = find(e[0]), b = find(e[1]);
if (a == b) return false; // cycle
parent[a] = b;
}
return true;
}
}; Time O((n + e) * alpha(n)) Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.