forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnhistory.js
More file actions
46 lines (39 loc) · 931 Bytes
/
nhistory.js
File metadata and controls
46 lines (39 loc) · 931 Bytes
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
class Solution {
/**
* @param {number} n
* @param {number[][]} edges
* @returns {boolean}
*/
validTree(n, edges) {
// A valid tree must have exactly n - 1 edges
if (edges.length !== n - 1) {
return false;
}
// Initialize the adjacency list
let graph = [];
for (let i = 0; i < n; i++) {
graph.push([]);
}
// Populate the adjacency list with edges
for (let [node, neighbor] of edges) {
graph[node].push(neighbor);
graph[neighbor].push(node);
}
let visited = new Set();
// Depth-First Search (DFS) to explore the graph
function dfs(node) {
visited.add(node);
for (let neighbor of graph[node]) {
if (!visited.has(neighbor)) {
dfs(neighbor);
}
}
}
// Start DFS from node 0
dfs(0);
// Check if all nodes were visited
return visited.size === n;
}
}
// TC: O(n)
// SC: O(n)