Formatted question description: https://leetcode.ca/all/508.html

508. Most Frequent Subtree Sum

Medium

Description

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

Do breadth first search and find the parent node of each node. Then loop over all nodes in the reversing order, and add each node’s value to its parent’s value. After this process, all nodes’ values become the subtree sums of the nodes. Find the most frequent subtree sums, obtain the subtree sums that are most frequent, and return.

• /**
* 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];
List<TreeNode> nodesList = new ArrayList<TreeNode>();
Map<TreeNode, TreeNode> childParentMap = new HashMap<TreeNode, TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
TreeNode left = node.left, right = node.right;
if (left != null) {
childParentMap.put(left, node);
queue.offer(left);
}
if (right != null) {
childParentMap.put(right, node);
queue.offer(right);
}
}
int maxCount = 0;
Map<Integer, Integer> sumCountMap = new HashMap<Integer, Integer>();
for (int i = nodesList.size() - 1; i >= 0; i--) {
TreeNode node = nodesList.get(i);
TreeNode parent = childParentMap.get(node);
if (parent != null)
parent.val += node.val;
int value = node.val;
int count = sumCountMap.getOrDefault(value, 0);
count++;
maxCount = Math.max(maxCount, count);
sumCountMap.put(value, count);
}
List<Integer> frequentSumsList = new ArrayList<Integer>();
Set<Integer> valuesSet = sumCountMap.keySet();
for (int value : valuesSet) {
int count = sumCountMap.getOrDefault(value, 0);
if (count == maxCount)
}
int length = frequentSumsList.size();
int[] frequentSums = new int[length];
for (int i = 0; i < length; i++)
frequentSums[i] = frequentSumsList.get(i);
return frequentSums;
}
}

• // OJ: https://leetcode.com/problems/most-frequent-subtree-sum/
// Time: O(logN)
// Space: O(N)
class Solution {
public:
vector<int> findFrequentTreeSum(TreeNode* root) {
vector<int> ans;
int maxFreq = 0;
unordered_map<int, int> m;
function<int(TreeNode*)> dfs = [&](TreeNode *root) {
if (!root) return 0;
int left = dfs(root->left), right = dfs(root->right), sum = left + right + root->val, f = ++m[sum];
if (f > maxFreq) maxFreq = f, ans = {sum};
else if (f == maxFreq) ans.push_back(sum);
return sum;
};
dfs(root);
return ans;
}
};

• # Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
def dfs(root):
if root is None:
return 0
left, right = dfs(root.left), dfs(root.right)
s = root.val + left + right
counter[s] += 1
return s

counter = Counter()
dfs(root)
mx = max(counter.values())
return [k for k, v in counter.items() if v == mx]

############

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def findFrequentTreeSum(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""

def helper(root, d):
if not root:
return 0
left = helper(root.left, d)
right = helper(root.right, d)
subtreeSum = left + right + root.val
d[subtreeSum] = d.get(subtreeSum, 0) + 1
return subtreeSum

d = {}
helper(root, d)
mostFreq = 0
ans = []
for key in d:
if d[key] > mostFreq:
mostFreq = d[key]
ans = [key]
elif d[key] == mostFreq:
ans.append(key)
return ans


• /**
* Definition for a binary tree node.
* type TreeNode struct {
*     Val int
*     Left *TreeNode
*     Right *TreeNode
* }
*/
func findFrequentTreeSum(root *TreeNode) []int {
counter := make(map[int]int)
mx := 0
var dfs func(root *TreeNode) int
dfs = func(root *TreeNode) int {
if root == nil {
return 0
}
s := root.Val + dfs(root.Left) + dfs(root.Right)
counter[s]++
if mx < counter[s] {
mx = counter[s]
}
return s
}
dfs(root)
var ans []int
for k, v := range counter {
if v == mx {
ans = append(ans, k)
}
}
return ans
}

• /**
* Definition for a binary tree node.
* class TreeNode {
*     val: number
*     left: TreeNode | null
*     right: TreeNode | null
*     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
*         this.val = (val===undefined ? 0 : val)
*         this.left = (left===undefined ? null : left)
*         this.right = (right===undefined ? null : right)
*     }
* }
*/

function findFrequentTreeSum(root: TreeNode | null): number[] {
const map = new Map<number, number>();
let max = 0;
const dfs = (root: TreeNode | null) => {
if (root == null) {
return 0;
}
const { val, left, right } = root;
const sum = val + dfs(left) + dfs(right);
map.set(sum, (map.get(sum) ?? 0) + 1);
max = Math.max(max, map.get(sum));
return sum;
};
dfs(root);
const res = [];
for (const [k, v] of map) {
if (v === max) {
res.push(k);
}
}
return res;
}


• // Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
impl Solution {
fn dfs(
root: &Option<Rc<RefCell<TreeNode>>>,
map: &mut HashMap<i32, i32>,
max: &mut i32,
) -> i32 {
if root.is_none() {
return 0;
}
let node = root.as_ref().unwrap().borrow();
let sum = node.val + Self::dfs(&node.left, map, max) + Self::dfs(&node.right, map, max);
map.insert(sum, map.get(&sum).unwrap_or(&0) + 1);
*max = (*max).max(map[&sum]);
sum
}

pub fn find_frequent_tree_sum(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut map = HashMap::new();
let mut max = 0;
let mut res = Vec::new();
Self::dfs(&root, &mut map, &mut max);
for (k, v) in map.into_iter() {
if v == max {
res.push(k);
}
}
res
}
}