Leetcode 508. Most Frequent Subtree Sum

Roger Wang
2 min readDec 1, 2017

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

DFS to record every node’s sum.

Runtime: 78 ms

# Definition for a binary tree node.
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val)
# @val = val
# @left, @right = nil, nil
# end
# end
# @param {TreeNode} root
# @return {Integer[]}
def find_frequent_tree_sum(root)
@hash = Hash.new
dfs root
max = 0
@hash.each do |h|
max = h[1] if h[1] > max
end

max = @hash.values.max
@hash.map{ |key, value| value == max ? key : nil }.compact
end
def dfs(node)
return 0 if node.nil?
sum = node.val
sum += dfs(node.left)
sum += dfs(node.right)

if @hash[sum].nil?
@hash[sum] = 1
else
@hash[sum] += 1
end
sum
end

Your runtime beats 100.00 % of ruby submissions.

--

--

No responses yet