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 ]
Difficulty
and has an acceptance rate of about 70% (200k+ submissions).
Typical patterns to solve this problem:
- Binary Tree
- Depth First Search
- Hash Table
- Tree
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 572: Subtree of Another Tree
- problem 1973: Count Nodes Equal to Sum of Descendants
Solved On The Same Day
- problem 144: Binary Tree Preorder Traversal
- problem 145: Binary Tree Postorder Traversal
- problem 222: Count Complete Tree Nodes
- problem 404: Sum of Left Leaves
- problem 501: Find Mode in Binary Search Tree
- problem 543: Diameter of Binary Tree
- problem 559: Maximum Depth of N-ary Tree
- problem 589: N-ary Tree Preorder Traversal
- problem 590: N-ary Tree Postorder Traversal
- problem 637: Average of Levels in Binary Tree
- problem 700: Search in a Binary Search Tree
- problem 703: Kth Largest Element in a Stream
- problem 79: Word Search
- problem 81: Search in Rotated Sorted Array II
- problem 97: Interleaving String
- problem 99: Recover Binary Search Tree
- problem 173: Binary Search Tree Iterator
- problem 199: Binary Tree Right Side View
- problem 230: Kth Smallest Element in a BST
- problem 235: Lowest Common Ancestor of a Binary Search Tree
- problem 341: Flatten Nested List Iterator
- problem 429: N-ary Tree Level Order Traversal
- problem 513: Find Bottom Left Tree Value
- problem 538: Convert BST to Greater Tree
- problem 65: Valid Number
- problem 85: Maximal Rectangle
- problem 87: Scramble String
- problem 126: Word Ladder II
- problem 127: Word Ladder
Extra
- 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