Problem statement

https://binarysearch.com/problems/Most-Frequent-Subtree-Sum/

Solution

Equal to Leetcode 0508 Most Frequent Subtree Sum

Complexity

It is O(n) for time and space.

Code

class Solution:
    def solve(self, root):
        cnt = Counter()
        
        def dfs(node):
            if not node: return 0
            ans = node.val + dfs(node.left) + dfs(node.right)
            cnt[ans] += 1
            return ans
        
        dfs(root)
        return cnt.most_common(1)[0][0]