-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgraphValidTree.js
More file actions
81 lines (66 loc) · 1.73 KB
/
graphValidTree.js
File metadata and controls
81 lines (66 loc) · 1.73 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
https://leetcode.com/problems/graph-valid-tree/description
Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
Example 1:
Input:
n = 5
edges = [[0, 1], [0, 2], [0, 3], [1, 4]]
Output:
true
Example 2:
Input:
n = 5
edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]
Output:
false
Note:
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
Constraints:
1 <= n <= 100
0 <= edges.length <= n * (n - 1) / 2
*/
class Node {
/**
*
* @param {number} val
*/
constructor(val) {
this.val = val;
this.neighbors = [];
}
/**
* @param {Node} node
*/
setNeighbor(node) {
this.neighbors.push(node);
}
}
/**
* @param {number} n
* @param {number[][]} edges
* @returns {boolean}
*/
const validTree = (n, edges) => {
const nodes = {};
Array.from({ length: n }, (_, i) => nodes[i] = new Node(i));
for (const [node1, node2] of edges) {
nodes[node1].setNeighbor(nodes[node2]);
nodes[node2].setNeighbor(nodes[node1]);
}
const stack = [[nodes[0], -Infinity]];
const visited = {};
while (stack.length) {
const [node, prev] = stack.pop();
if (visited[node.val]) {
return false;
}
visited[node.val] = true;
for (const neighbor of node.neighbors) {
if (neighbor.val !== prev) {
stack.push([neighbor, node.val]);
}
}
}
return Object.keys(nodes).length === Object.keys(visited).length;
}
module.exports = { validTree };