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)]
Difficulty
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
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 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
nodeexists; aNonereference terminates that branch immediately. - The current node’s value is stored (or overwritten) in
leftusing the currentdepthas 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 aNonechild, 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.valon 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.
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.
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 | 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++ |
Videos
Similar Problems
- problem 515: Find Largest Value in Each Tree Row
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 508: Most Frequent Subtree Sum
- 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