File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number } nodes
3+ * @param {number[] } parent
4+ * @param {number[] } value
5+ * @return {number }
6+ */
7+ const deleteTreeNodes = function ( nodes , parent , value ) {
8+ const n = nodes
9+ const hash = { }
10+ hash [ 0 ] = new Node ( value [ 0 ] )
11+ for ( let i = 1 ; i < n ; i ++ ) {
12+ hash [ i ] = new Node ( value [ i ] )
13+ }
14+
15+ for ( let i = 1 ; i < n ; i ++ ) {
16+ const p = parent [ i ]
17+ hash [ p ] . children [ i ] = hash [ i ]
18+ }
19+
20+ const r = hash [ 0 ]
21+ dfs ( r )
22+ // console.log(n)
23+ return cnt ( r )
24+
25+ function dfs ( node ) {
26+ if ( node == null ) return 0
27+ let res = node . sum
28+
29+ const keys = Object . keys ( node . children )
30+ for ( const k of keys ) {
31+ res += dfs ( hash [ k ] )
32+ }
33+
34+ node . sum = res
35+ return res
36+ }
37+
38+ function cnt ( node ) {
39+ if ( node == null ) return 0
40+ if ( node . sum === 0 ) return 0
41+ const keys = Object . keys ( node . children )
42+ let res = 1
43+ for ( const k of keys ) {
44+ res += cnt ( hash [ k ] )
45+ }
46+
47+ return res
48+ }
49+ }
50+
51+ class Node {
52+ constructor ( v ) {
53+ this . val = v
54+ this . sum = v
55+ this . children = { }
56+ }
57+ }
You can’t perform that action at this time.
0 commit comments