-
Notifications
You must be signed in to change notification settings - Fork 0
/
prac1.js
111 lines (97 loc) · 2.34 KB
/
prac1.js
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
https://dpaste.org/0ujw
https://dpaste.org/0ujw
About History New snippet
JavaScript Expires in: 8 hours, 55 minutes
Delete Now
Raw
Slim
class Node {
constructor(val, children) {
this.val = val;
this.children = children;
}
}
function solve(root) {
if (!root) return null;
let maxAverage = 0;
let ret = null;
function dfs(node) {
if (!node) return [0, 0];
let totalCount = 1;
let totalSum = node.val;
node.children.forEach((child) => {
let [subCount, subSum] = dfs(child);
totalCount += subCount;
totalSum += subSum;
});
let currAverage = totalSum / totalCount;
if (currAverage > maxAverage && totalCount > 1) {
maxAverage = currAverage;
ret = node;
}
return [totalCount, totalSum];
}
dfs(root);
return ret;
}
const node11 = new Node(11, []);
const node2 = new Node(2, []);
const node3 = new Node(3, []);
const node12 = new Node(12, [node11, node2, node3]);
const node15 = new Node(15, []);
const node8 = new Node(8, []);
const node18 = new Node(18, [node15, node8]);
const root = new Node(20, [node12, node18]);
console.log(solve(root));
Copy Snippet
Edit Snippet
Wordwrap
class Node {
constructor(val, children) {
this.val = val;
this.children = children;
}
}
function solve(root) {
if (!root) return null;
let maxAverage = 0;
let ret = null;
function dfs(node) {
if (!node) return [0, 0];
let totalCount = 1;
let totalSum = node.val;
node.children.forEach((child) => {
let [subCount, subSum] = dfs(child);
totalCount += subCount;
totalSum += subSum;
});
let currAverage = totalSum / totalCount;
if (currAverage > maxAverage && totalCount > 1) {
maxAverage = currAverage;
ret = node;
}
return [totalCount, totalSum];
}
dfs(root);
return ret;
}
const node11 = new Node(11, []);
const node2 = new Node(2, []);
const node3 = new Node(3, []);
const node12 = new Node(12, [node11, node2, node3]);
const node15 = new Node(15, []);
const node8 = new Node(8, []);
const node18 = new Node(18, [node15, node8]);
const root = new Node(20, [node12, node18]);
console.log(solve(root));