{"type": "session", "harness": "opencode", "id": "cp-10017", "name": "LeetCode 0508: Most Frequent Subtree Sum"} {"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}} {"type": "message", "message": {"role": "user", "content": "Problem: Most Frequent Subtree Sum (Difficulty: Medium)\nTags: Hash Table, Tree, Depth-First Search, Binary Tree\n\nGiven 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.\nThe 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).\n\nExample 1:\nInput: root = [5,2,-3]\nOutput: [2,-3,4]\n\nExample 2:\nInput: root = [5,2,-5]\nOutput: [2]\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 104].\n- -10^5 <= Node.val <= 10^5"}} {"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(n)\n\nimport collections\n\n\nclass Solution(object):\n def findFrequentTreeSum(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n def countSubtreeSumHelper(root, counts):\n if not root:\n return 0\n total = root.val + \\\n countSubtreeSumHelper(root.left, counts) + \\\n countSubtreeSumHelper(root.right, counts)\n counts[total] += 1\n return total\n\n counts = collections.defaultdict(int)\n countSubtreeSumHelper(root, counts)\n max_count = max(counts.values()) if counts else 0\n return [total for total, count in counts.iteritems() if count == max_count]\n\n"}}