TikTok Interview Question: Most Frequent Subtree Sum in a 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).
这道题的关键在于对每个节点计算“以它为根的子树节点值总和”,然后统计这些和出现的次数。因为子树和依赖左右子树的结果,通常使用后序遍历来计算。在递归过程中,用哈希表记录每个子树和的出现频率,遍历完成后再找出出现次数最多的那个(或多个)。本质是 DFS + 频率统计的结合。