Skip to content

Commit 83370d8

Browse files
authored
Update 2003-smallest-missing-genetic-value-in-each-subtree.js
1 parent a096f7e commit 83370d8

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

2003-smallest-missing-genetic-value-in-each-subtree.js

+58
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,61 @@
1+
/**
2+
* @param {number[]} parents
3+
* @param {number[]} nums
4+
* @return {number[]}
5+
*/
6+
function smallestMissingValueSubtree(parent, nums) {
7+
const graph = {},
8+
n = parent.length
9+
const res = Array(n).fill(1)
10+
const visited = new Set()
11+
let miss = 1
12+
for (let i = 0; i < n; i++) {
13+
if (graph[parent[i]] == null) graph[parent[i]] = []
14+
graph[parent[i]].push(i)
15+
}
16+
let idx = -1
17+
for (let i = 0; i < n; i++) {
18+
if (nums[i] === 1) {
19+
idx = i
20+
break
21+
}
22+
}
23+
24+
if (idx === -1) return res
25+
let cur = idx,
26+
pre = -1
27+
while (cur !== -1) {
28+
const chidlren = graph[cur]
29+
if (chidlren) {
30+
for (const child of chidlren) {
31+
if (child === pre) continue
32+
dfs(child)
33+
}
34+
}
35+
visited.add(nums[cur])
36+
while (visited.has(miss)) {
37+
miss++
38+
}
39+
// console.log(cur, miss, visited)
40+
res[cur] = miss
41+
pre = cur
42+
cur = parent[cur]
43+
}
44+
45+
return res
46+
47+
function dfs(node) {
48+
visited.add(nums[node])
49+
const chidlren = graph[node]
50+
if (chidlren) {
51+
for (const child of chidlren) dfs(child)
52+
}
53+
}
54+
}
55+
56+
// another
57+
58+
159
/**
260
* @param {number[]} parents
361
* @param {number[]} nums

0 commit comments

Comments
 (0)