forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTessa1217.java
More file actions
57 lines (45 loc) · 1.34 KB
/
Tessa1217.java
File metadata and controls
57 lines (45 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class Solution {
/**
* @param n: An integer
* @param edges: a list of undirected edges
* @return: true if it's a valid tree, or false
*/
// 시간 복잡도: O(n), 공간복잡도: O(n)
public boolean validTree(int n, int[][] edges) {
if (edges.length != (n - 1)) {
return false;
}
List<Integer>[] graph = new ArrayList[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
for (int[] edge : edges) {
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
boolean[] visited = new boolean[n];
if (!dfs(0, -1, visited, graph)) {
return false;
}
for (boolean v : visited) {
if (!v) {
return false; // Not fully connected
}
}
return true;
}
private boolean dfs(int node, int parent, boolean[] visited, List<Integer>[] graph) {
if (visited[node]) {
return false; // Found a cycle
}
visited[node] = true;
for (int neighbor : graph[node]) {
if (neighbor != parent) {
if (!dfs(neighbor, node, visited, graph)) {
return false;
}
}
}
return true;
}
}