> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Most Frequent Subtree Sum Python Solution

> Tested Python solution for LeetCode 508 with 22 pytest cases. Generate a practice environment with lcpy.

LeetCode 508, [Medium](/catalog/medium). Topics: [Hash Table](/catalog/topics/hash-table), [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Binary Tree](/catalog/topics/binary-tree), DP on Trees. [View on LeetCode](https://leetcode.com/problems/most-frequent-subtree-sum/description/).

Generate this problem as a practice environment: tested reference solution, 22 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 508   # by problem number
lcpy gen -s most_frequent_subtree_sum   # by problem name
```

## Problem

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).

### Examples

![Example 1](https://assets.leetcode.com/uploads/2021/04/24/freq1-tree.jpg)

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

![Example 2](https://assets.leetcode.com/uploads/2021/04/24/freq2-tree.jpg)

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

### Constraints

* The number of nodes in the tree is in the range \[1, 10^4]
* -10^5 \<= Node.val \<= 10^5

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/most_frequent_subtree_sum/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/most_frequent_subtree_sum/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import Counter

from leetcode_py import TreeNode


class Solution:
    # Time: O(n), each node visited once; result collection O(distinct sums)
    # Space: O(n) for the recursion stack and the counter
    def find_frequent_tree_sum(self, root: TreeNode[int] | None) -> list[int]:
        counts: Counter[int] = Counter()

        def dfs(node: TreeNode[int] | None) -> int:
            if node is None:
                return 0
            total = node.val + dfs(node.left) + dfs(node.right)
            counts[total] += 1
            return total

        dfs(root)
        top = max(counts.values())
        return [total for total, count in counts.items() if count == top]
```

## Complexity

| Time | Space |
| - | - |
| O(n), each node visited once; result collection O(distinct sums) | O(n) for the recursion stack and the counter |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.