Problem 513

Abstract / Summary

Find the value of the leftmost node at the deepest level of a binary tree.

Note

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

Python 0513.py

class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        left = {}

        def deeper(node, depth):
            if node:
                left[depth] = node.val
                # order matters !
                deeper(node.right, depth + 1)
                deeper(node.left,  depth + 1)

        deeper(root, 0)
        return left[max(left)]
13 lines | 391 bytes | submitted September 1, 2023 | GitHub   10% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 71% (500k+ 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 solves the “bottom-left value” problem for a binary tree. It performs a depth-first traversal that records, for each depth, the most recent node value encountered. By visiting the right subtree before the left subtree, the algorithm guarantees that the leftmost node at any depth overwrites earlier entries. After the traversal finishes, the value stored for the greatest depth is returned, which corresponds to the bottom-leftmost node of the tree.

Core Logic

The algorithm revolves around three distinct steps: initialization of the storage container, recursive depth-first exploration with a specific child order, and extraction of the result from the populated container.

Initialization

left = {}

A plain dictionary is created to map each depth level to a node value. Because only one value per depth is needed, the dictionary remains compact regardless of tree size.

Recursive Traversal

def deeper(node, depth):
    if node:
        left[depth] = node.val
        # order matters !
        deeper(node.right, depth + 1)
        deeper(node.left,  depth + 1)
  • The function checks whether the current node exists; a None reference terminates that branch immediately.
  • The current node’s value is stored (or overwritten) in left using the current depth as the key.
  • The right child is visited first, followed by the left child. This ordering ensures that when both children exist at the same depth, the left child’s value will replace the right child’s value in the dictionary, leaving the leftmost node’s value as the final entry for that depth.

The recursion is initiated with the root node at depth 0:

deeper(root, 0)

Result Extraction

return left[max(left)]

max(left) yields the deepest depth encountered during traversal. The dictionary entry for that depth holds the leftmost node’s value at the deepest level, which is returned as the answer.

Edge-Case Handling

  • Single-Node Tree - When the tree consists of only the root, the recursion stores the root’s value at depth 0. max(left) evaluates to 0, and the function returns the root’s value, correctly handling the minimal non-empty case.
  • Unbalanced Trees - The depth-first approach naturally follows any shape of binary tree, whether heavily skewed to the left or right. Because the algorithm records values per depth without assuming balanced structure, it correctly identifies the bottom-leftmost node even when the deepest leaf lies far deeper on one side.
  • Missing Children - The guard if node: prevents attempts to access attributes of a None child, so branches that terminate early simply return without affecting the dictionary. This implicit handling avoids extra conditional logic for left or right child presence.

Performance Optimizations

The implementation achieves efficiency through several deliberate choices:

  • In-Place Overwrite - By assigning left[depth] = node.val on every visit, the algorithm avoids maintaining a list of all nodes at a given depth. Overwrites replace earlier values, eliminating the need for additional comparisons or data structures to track the leftmost element.
  • Tailored Traversal Order - Visiting the right subtree before the left subtree removes the necessity for a separate pass to locate the leftmost node at each depth. The ordering itself guarantees that the final stored value for any depth is the leftmost one, reducing overall work.
  • Dictionary Access - Dictionary look-ups and assignments are O(1) on average, so each node contributes a constant amount of work. The storage grows only with the number of distinct depths, which is bounded by the height of the tree, not by the total node count.
  • Recursive Stack Utilization - The recursion depth matches the tree height, using the call stack as the sole auxiliary structure. No explicit queue or stack is allocated, keeping memory overhead minimal.

Through these mechanisms, the solution processes each node exactly once while maintaining a compact representation of the necessary information, delivering a fast and memory-light answer to the bottom-left value problem.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a tall tree made of wood blocks. Each block has a special number written on it. Some blocks have branches that lead to other blocks below them. The goal is to find the very bottom block on the far left side of the tree.

The code works by exploring the tree one floor at a time, moving from the top down to the ground. A helper tool keeps a notepad to write down the number of the block it sees at each floor. It visits the right side of the tree first and then the left side. Because it writes down the number whenever it visits a new spot, the left side always overwrites anything that was written before it for that specific floor.

At the end of the journey, the notepad contains the numbers for every floor. Since the code saved the left-most block last for each height, the very bottom of the notepad holds the answer for the lowest level of the tree.

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 | μ = 6.19 | σ = 1.79

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 Python Rust Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fengvyi C++
gouthampradhan Java
halfrost Go
JoshCrozier JS
Krazune C++
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
YuriSpiridonov Python
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
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fengvyi C++
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
Krazune C++
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
YuriSpiridonov Python
zfang399 C++
37 links | 23 authors | 9 languages

Videos

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

Similar Problems

1 similar problem

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