Practice › Graphs
Is the Graph a Tree
Easy · Graphs · Asked at Amazon, Google, Microsoft, LinkedIn
Print YES if the undirected graph is a tree — connected and without cycles — otherwise NO.
Input
First line: n m. Next m lines: u v (no self-loops or repeated edges).
Output
YES or NO.
Constraints
- 1 ≤ n ≤ 10^5
- 0 ≤ m ≤ 10^5
A tree on n nodes has exactly n − 1 edges. If m ≠ n − 1 the answer is NO; otherwise it is a tree exactly when it is connected (check with BFS or a disjoint-set union).
Example 1
Input
5 4 1 2 1 3 1 4 4 5
Output
YES
Example 2
Input
5 4 1 2 2 3 3 1 4 5
Output
NO
Hints
- A tree with n nodes has exactly n − 1 edges.
- With n − 1 edges, "connected" and "no cycle" are equivalent.
- A disjoint-set union detects a cycle the moment an edge joins two already-connected nodes.
Approach
If m ≠ n − 1, print NO. Otherwise add the edges to a DSU; if any edge connects two nodes that are already in the same set, there is a cycle — NO. If all n − 1 edges join different sets, the graph is connected and acyclic — YES.
Complexity: O((n + m) α(n)) time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
vector<int> parent;
int find(int x) {
while (parent[x] != x) x = parent[x] = parent[parent[x]];
return x;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
if (m != n - 1) {
cout << "NO\n";
return 0;
}
parent.resize(n + 1);
iota(parent.begin(), parent.end(), 0);
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
int a = find(u), b = find(v);
if (a == b) {
cout << "NO\n";
return 0;
}
parent[a] = b;
}
cout << "YES\n";
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n, m = data[0], data[1]
parent = list(range(n + 1))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
ok = m == n - 1
if ok:
for i in range(m):
a, b = find(data[2 + 2 * i]), find(data[3 + 2 * i])
if a == b:
ok = False
break
parent[a] = b
print("YES" if ok else "NO")Java solution
import java.io.*;
public class Main {
static int[] parent;
static int find(int x) {
while (parent[x] != x) x = parent[x] = parent[parent[x]];
return x;
}
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
int m = (int) in.nval;
if (m != n - 1) {
System.out.println("NO");
return;
}
parent = new int[n + 1];
for (int i = 0; i <= n; i++) parent[i] = i;
for (int i = 0; i < m; i++) {
in.nextToken();
int a = find((int) in.nval);
in.nextToken();
int b = find((int) in.nval);
if (a == b) {
System.out.println("NO");
return;
}
parent[a] = b;
}
System.out.println("YES");
}
}