508 Most Frequent Subtree Sum
1. Question
5
/ \
2 -3 5
/ \
2 -52. Implementation
3. Time & Space Complexity
Last updated
5
/ \
2 -3 5
/ \
2 -5Last updated
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int[] findFrequentTreeSum(TreeNode root) {
if (root == null) {
return new int[0];
}
int[] max = new int[1];
Map<Integer, Integer> map = new HashMap();
findSubTreeSumByDFS(root, map, max);
List<Integer> list = new ArrayList();
for (int key : map.keySet()) {
if (map.get(key) == max[0]) {
list.add(key);
}
}
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
public int findSubTreeSumByDFS(TreeNode node, Map<Integer, Integer> map, int[] max) {
if (node == null) {
return 0;
}
int leftSum = findSubTreeSumByDFS(node.left, map, max);
int rightSum = findSubTreeSumByDFS(node.right, map, max);
int sum = node.val + leftSum + rightSum;
map.put(sum, map.getOrDefault(sum, 0) + 1);
max[0] = Math.max(max[0], map.get(sum));
return sum;
}
}