-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.js
48 lines (40 loc) · 1012 Bytes
/
solution.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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
// 后序遍历
var findFrequentTreeSum = function (root) {
if (root === null) {
return [];
}
const map = {};
function divideConquer (node) {
const left = (node.left && divideConquer(node.left)) || 0;
const right = (node.right && divideConquer(node.right)) || 0;
const sum = left + right + node.val;
if (map[sum] === undefined) {
map[sum] = 0;
}
map[sum]++;
return sum;
}
divideConquer(root);
const map2 = {};
const counts = [];
Object.keys(map).forEach((num) => {
const count = map[num];
counts.push(count);
if (map2[count] === undefined) {
map2[count] = [];
}
map2[count].push(+num);
});
return map2[Math.max.apply(null, counts)];
};