Problem 508

Abstract / Summary

Find the sum that occurs most often when adding up all node values in every possible subtree of a binary tree.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0508.py

class Solution:
    def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:
        sums = defaultdict(int)

        def deeper(node):
            if not node:
                return 0

            current = node.val + deeper(node.left) + deeper(node.right)
            sums[current] += 1
            return current

        deeper(root)

        high = max(sums.values())
        return [ i for i in sums if sums[i] == high ]
16 lines | 457 bytes | submitted September 1, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 70% (200k+ submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Depth First Search
  • Hash Table
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation defines a class method that computes the most frequent subtree sum(s) of a binary tree. A subtree sum is the total of all node values within a given subtree, including the root of that subtree. The algorithm performs a single depth-first traversal, records each encountered sum in a hash map, determines the highest occurrence count, and finally extracts all sums that share this maximum frequency.

Core Logic

The method begins by creating a hash map that automatically initializes missing keys to zero. This map, named sums, stores each distinct subtree sum as a key and the number of times it appears as the associated value.

sums = defaultdict(int)

A nested helper function, deeper, carries out the recursive depth-first search. For a null node the function returns zero, which correctly contributes nothing to the parent’s sum. For a non-null node the function computes the sum of the current node’s value together with the sums returned from its left and right children. Immediately after computing this value, the function increments the corresponding entry in sums.

def deeper(node):
    if not node:
        return 0

    current = node.val + deeper(node.left) + deeper(node.right)
    sums[current] += 1
    return current

The recursion is initiated with the original tree root, ensuring that every possible subtree is visited exactly once.

deeper(root)

After the traversal, the algorithm identifies the maximum frequency among all recorded sums. It then builds a list containing every sum whose frequency matches this maximum. The list comprehension iterates over the keys of sums and selects those with the highest count.

high = max(sums.values())
return [i for i in sums if sums[i] == high]

Edge Cases Handled

When a node is a leaf, both recursive calls on its children return zero, so the leaf’s own value becomes the subtree sum. The code correctly records this sum and counts it.

If the tree consists of a single node, the recursion still executes once, registers the node’s value as the only subtree sum, and returns it as the sole element of the result list.

The use of defaultdict(int) guarantees that any newly encountered sum can be incremented without first checking for its existence, which gracefully handles the first occurrence of any sum value.

Performance Optimizations

The algorithm achieves efficiency by combining traversal and aggregation in a single pass. Each node is visited exactly once, and the sum for each subtree is computed on the fly, eliminating the need for auxiliary storage of intermediate results.

The hash map provides constant-time updates and lookups for sum frequencies, ensuring that the bookkeeping overhead does not grow with the size of the tree beyond the number of distinct sums.

The final extraction of the most frequent sums uses a list comprehension, which iterates over the map’s keys only once and constructs the output list without additional loops or temporary collections.

Overall, the design leverages recursion, a default-initialized dictionary, and concise comprehension syntax to keep both runtime work and memory usage minimal while delivering the required result.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a giant tree made of numbers where every branch has its own special value. To solve this puzzle, a little helper starts at the very top of the tree and travels down to every single leaf.

As the helper moves, it adds the value of a branch to everything it finds growing below that branch. It keeps a tally of all these different totals in a notebook. Every time a new total is calculated, a mark goes into the notebook next to that number.

After checking every single branch, the helper looks at the notebook to see which total shows up the most often. It identifies the highest count among all the totals. Finally, it gathers all the numbers that hold that top spot and puts them together into a final collection.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.85 | σ = 0.76

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Rust Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fengvyi C++
gouthampradhan Java
halfrost Go
JoshCrozier JS
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fengvyi C++
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
zfang399 C++
33 links | 19 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

30 solutions   September 1, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality