<jupyter_start><jupyter_text>说明：    给你一个二叉树的根结点，请你找出出现次数最多的子树元素和。    一个结点的「子树元素和」定义为以该结点为根的二叉树上所有结点的元素之和（包括结点本身）。    你需要返回出现次数最多的子树元素和。如    果有多个元素出现的次数相同，返回所有出现次数最多的子树元素和（不限顺序）。示例 1：    输入:          5         /  \        2   -3    返回 [2, -3, 4]，所有的值均只出现一次，以任意顺序返回所有值。示例 2：    输入：          5         /  \        2   -5    返回 [2]，只有 2 出现两次，-5 只出现 1 次。提示： 假设任意子树元素和均可以用 32 位有符号整数表示。<jupyter_code>vals_dict = {1:2, 2:3, 3:4}
vals_freq = sorted(vals_dict.items(), key=lambda x: -x[1])
res, most_val = [], 1
for val, freq in vals_freq:
    if freq >= most_val:
        most_val = freq
        res.append(val)
    else:
        break
print(res)
class Solution:
    def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
        def postorder(root):
            if not root: 
                return 0
            total = root.val + postorder(root.left) + postorder(root.right) 
            self.freqs[total] = 1 + self.freqs.get(total, 0)
            return total
        
        if not root: 
            return []
        self.freqs = {}
        postorder(root)
        mostFreq = max(self.freqs.values())
        sums = [ total for total, count in self.freqs.items() if count == mostFreq ]
        return sums
from collections import defaultdict

# 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]:
        vals_dict = defaultdict(int)
        
        def dfs(node):
            nonlocal vals_dict
            if not node:
                return 0
            l = dfs(node.left)
            r = dfs(node.right)
            vals_dict[l + r + node.val] += 1
            return l + r + node.val
        
        dfs(root)
        if not vals_dict:
            return []
        max_freq = max(vals_dict.values())
        res = [key for key, val in vals_dict if key == max_freq]
        return res<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10801564027370479, 'fraction_numerical': 0.015151515151515152, 'mean_word_length': 1.862937062937063, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '344267', 'license': 'Apache-2.0', 'n_tokens_mistral': 829, 'n_tokens_neox': 829, 'n_words': 170, 'path': 'Tree/1020/508. Most Frequent Subtree Sum.ipynb', 'repo_name': 'YuHe0108/Leetcode', 'size': '2046'}