Problem 1302

Abstract / Summary

Find the sum of all nodes at the maximum depth in a binary tree.

Note

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

Python 1302.py

class Solution:
    def deepestLeavesSum(self, root: Optional[TreeNode]) -> int:
        total = defaultdict(int)
        def deeper(node, depth):
            if node:
                total[depth] += node.val
                deeper(node.left,  depth + 1)
                deeper(node.right, depth + 1)

        deeper(root, 0)
        return total[max(total)]
11 lines | 370 bytes | submitted October 19, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 87% (400k+ submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Breadth First Search
  • Depth First Search
  • 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 provided implementation defines a Solution class with a method deepestLeavesSum that computes the sum of the values of the deepest leaf nodes in a binary tree. It leverages a depth-first traversal to accumulate node values grouped by their depth, then extracts the total for the greatest depth encountered.

Key Steps

Initialization of the Accumulator

A defaultdict of integers is created to store the cumulative sum for each depth level. The default value of 0 eliminates the need for explicit existence checks before updating the sum.

total = defaultdict(int)

Recursive Depth-First Traversal

An inner function deeper is defined to walk the tree recursively. For every non-null node, the function adds the node’s value to the accumulator entry corresponding to the current depth, then recurses on the left and right children with an incremented depth.

def deeper(node, depth):
    if node:
        total[depth] += node.val
        deeper(node.left,  depth + 1)
        deeper(node.right, depth + 1)

The initial call starts the traversal at the root with depth 0.

deeper(root, 0)

Extraction of the Deepest Level Sum

After the traversal completes, the dictionary total contains a sum for each depth that was visited. The deepest depth is identified by taking the maximum key, and the associated sum is returned as the final result.

return total[max(total)]

Edge Cases Handled

The recursive logic naturally accommodates trees of any shape:

  • Single-node tree - The root is processed at depth 0, and the sum for that depth is returned, correctly handling the minimal case.
  • Left-only or right-only chains - The recursion proceeds down the existing branch, accumulating values at each successive depth, ensuring that the deepest leaf (the terminal node) contributes its value to the final sum.
  • Highly unbalanced trees - Because the algorithm does not rely on balanced properties, it correctly aggregates values regardless of depth variance between subtrees.
  • Multiple deepest leaves - When several leaves share the maximum depth, each leaf’s value is added to the same depth entry in total, yielding the combined sum required.

Performance Optimizations

The implementation achieves efficiency through several design choices:

  • Single-pass aggregation - By updating the accumulator during the depth-first walk, the algorithm avoids a second pass over the collected data, reducing overall work.
  • Use of defaultdict - The automatic initialization of missing keys to 0 removes conditional checks, streamlining the addition operation.
  • In-place recursion - The traversal does not allocate auxiliary containers such as explicit stacks or queues; the call stack alone maintains traversal state, minimizing memory overhead.
  • Direct retrieval of the deepest sum - Computing max(total) after the traversal provides immediate access to the deepest level without scanning the tree again.
written by openai gpt

ELI5 - Simplified Explanation

Imagine a tree that grows upside down starting from a single point at the very top. Each spot in the tree holds a secret number. This code goes on a treasure hunt to find all the numbers tucked away at the very bottom of the tree.

First, a big empty bag is prepared to keep track of the numbers found at each level of the tree. The tree starts at depth zero, which is just the top point. Whenever an explorer visits a spot, they look at the number inside and put it into the bag marked with that specific depth. If there is a path leading to the left or to the right, the explorer travels down to the next level to keep searching.

The explorer keeps going deeper and deeper until there are no paths left to follow. Once every single spot has been visited, the bag contains sums of numbers for every level of the tree. The final step is to look at the bag and pick out the total sum from the deepest level where the explorers finished their journey.

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 = 7 | μ = 7.00 | σ = 1.33

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++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python Java Go C Rust TS
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C, C++, Go, Java, Python, Rust, TypeScript
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
35 links | 22 authors | 10 languages

Videos

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

Solved On The Same Day

8 solutions   October 19, 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