tinycodinglm / cp /cp-10017.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
1.8 kB
opencode trace
System You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

User

Problem: Most Frequent Subtree Sum (Difficulty: Medium)
Tags: Hash Table, Tree, Depth-First Search, Binary Tree

Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.
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).

Example 1:
Input: root = [5,2,-3]
Output: [2,-3,4]

Example 2:
Input: root = [5,2,-5]
Output: [2]

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -10^5 <= Node.val <= 10^5
Assistant

Time: O(n)

Space: O(n)

import collections

class Solution(object):
def findFrequentTreeSum(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def countSubtreeSumHelper(root, counts):
if not root:
return 0
total = root.val +
countSubtreeSumHelper(root.left, counts) +
countSubtreeSumHelper(root.right, counts)
counts[total] += 1
return total

markdown
counts = collections.defaultdict(int)
    countSubtreeSumHelper(root, counts)
    max_count = max(counts.values()) if counts else 0
    return [total for total, count in counts.iteritems() if count == max_count]