-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmost-frequent-subtree-sum.js
55 lines (47 loc) · 1.37 KB
/
most-frequent-subtree-sum.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
// https://leetcode.com/problems/most-frequent-subtree-sum/
// Related Topics: Hash Table, Tree, DFS
// Difficulty: Medium
/*
Initial thoughts:
Traversing the tree in a post order DFS manner, we are going to create
a freqency table of all the subtree sums and return those sums that occur
most at the end.
Time Complexity: O(n) where n == number of nodes in the tree
Space Complexity: O(n) where n == number of nodes in the tree (In a worst case
situation, each and every subtree has a unique sum that requires a separate entry
in our freqency table)
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
const findFrequentTreeSum = root => {
if (!root) return [];
const m = new Map();
function dfs(root) {
if (!root) return 0;
const left = dfs(root.left);
const right = dfs(root.right);
const val = root.val + left + right;
if (m.has(val)) m.set(val, m.get(val) + 1);
else m.set(val, 1);
return val;
}
dfs(root);
let max = Number.NEGATIVE_INFINITY;
let finalRes;
for (let [key, val] of m.entries()) {
if (val > max) {
max = val;
finalRes = [key];
} else if (val === max) finalRes.push(key);
}
return finalRes;
};