508. Most Frequent Subtree Sum
by Botao Xiao
508. Most Frequent Subtree Sum
Question
Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.
Examples 1
Input:
5
/ \
2 -3
return [2, -3, 4], since all the values happen only once, return all of them in any order.
Examples 2
Input:
5
/ \
2 -5
return [2], since 2 happens twice, however -5 only occur once.
Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.
Solution
- Method 1: dfs + Map
```Java
/**
- Definition for a binary tree node.
- public class TreeNode {
- int val;
- TreeNode left;
- TreeNode right;
- TreeNode(int x) { val = x; }
- }
*/
class Solution {
private Map<Integer, Integer> map;
private int max;
public int[] findFrequentTreeSum(TreeNode root) {
this.map = new HashMap<>();
if(root == null) return new int[]{};
getSubtreeSum(root);
List
res = new ArrayList<>(); for(Map.Entry<Integer, Integer> entry: map.entrySet()){ if(entry.getValue() == max){ res.add(entry.getKey()); } } int size = res.size(); int index = 0; int[] result = new int[size]; for(Integer n : res) result[index++] = n; return result; } private int getSubtreeSum(TreeNode node){ if(node.left == null && node.right == null){ int appear = map.containsKey(node.val) ? map.get(node.val): 0; map.put(node.val, appear + 1); max = Math.max(max, appear + 1); return node.val; }else{ int left = 0, right = 0; if(node.left != null) left = getSubtreeSum(node.left); if(node.right != null) right = getSubtreeSum(node.right); int sum = node.val + left + right; int appearSum = map.containsKey(sum) ? map.get(sum): 0; map.put(sum, appearSum + 1); max = Math.max(max, appearSum + 1); return sum; } } } ```
Subscribe via RSS