Python 0107.py
class Solution:
def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:
# similiar to problem 102
levels = defaultdict(list)
def deeper(node, depth):
if node:
levels[depth].append(node.val)
deeper(node.left, depth+1)
deeper(node.right, depth+1)
deeper(root, 0)
return reversed([ levels[l] for l in sorted(levels.keys()) ])
Difficulty
and has an acceptance rate of about 69% (1+ million submissions).
Typical patterns to solve this problem:
- Binary Tree
- Breadth 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 defines a Solution class with a single method levelOrderBottom. The method receives the root of a binary tree and returns a list of lists, where each inner list contains the node values at a particular depth, ordered from the deepest level up to the root. The algorithm follows a depth-first traversal to collect values per depth and then reorders the collected levels to satisfy the bottom-up requirement.
Core Logic
The first important step is the creation of a container that maps each depth to the list of node values encountered at that depth. The code uses a defaultdict with list as the default factory, which automatically creates an empty list for a new depth key.
levels = defaultdict(list)
The heart of the traversal is the nested helper function deeper. It receives a node and its current depth, appends the node’s value to the appropriate list in levels, and then recursively processes the left and right children, incrementing the depth by one for each recursive call.
def deeper(node, depth):
if node:
levels[depth].append(node.val)
deeper(node.left, depth+1)
deeper(node.right, depth+1)
The recursion is initiated with the original root node and a starting depth of 0.
deeper(root, 0)
After the traversal finishes, levels contains entries such as {0: [root.val], 1: [left.val, right.val], …}. The next phase extracts the lists in order of increasing depth, sorts the depth keys, and builds a list of the corresponding value lists.
[ levels[l] for l in sorted(levels.keys()) ]
Finally, the method returns a reversed view of that list, which yields the levels from the deepest to the shallowest without creating an additional reversed copy.
return reversed([ levels[l] for l in sorted(levels.keys()) ])
Edge Cases Handled
When the input tree is empty (root is None), the recursive helper deeper immediately returns without modifying levels. Consequently, levels remains empty, the list comprehension produces an empty list, and reversed applied to an empty list yields an empty iterator. The method therefore returns an empty result, correctly representing the absence of any levels.
If the tree consists of a single node, the recursion records the node’s value at depth 0. The sorted keys list contains only 0, the comprehension builds [[node.val]], and reversed yields the same single-element list in bottom-up order. This demonstrates correct handling of minimal non-empty trees.
The recursion also naturally accommodates unbalanced trees. Because depth is passed explicitly and each recursive call increments it, nodes at any depth are placed into the correct bucket regardless of the shape of the tree. The final sorting of depth keys guarantees that all levels appear in the proper order before reversal.
Performance Optimizations
The use of defaultdict(list) eliminates the need for explicit existence checks before appending to a depth bucket, reducing overhead in the inner loop of the traversal. By performing a single depth-first pass, the algorithm avoids the extra queue structure commonly employed in breadth-first traversals, thereby keeping the call stack as the only auxiliary data structure.
Collecting values during the recursive descent means each node is visited exactly once, and the work done per node is limited to a constant-time append operation and two recursive calls. The later sorting of depth keys operates on the number of distinct depths rather than on the total number of nodes, which is typically much smaller, keeping the overhead modest.
Returning reversed directly provides a lazy view of the list in reverse order. This avoids allocating a new list for the reversed sequence, saving both time and memory when the caller iterates over the result. The overall flow-single traversal, minimal per-node work, and a lazy reversal-constitutes an efficient solution for generating bottom-up level order traversals.
ELI5 - Simplified Explanation
Imagine a tree made of numbers where each branch splits into two more branches. To organize all these numbers, this code builds a digital shelf for them.
The process starts at the very top of the tree. A little helper function visits every single branch one by one, picking up the number it finds there. As it explores, it remembers how deep it went down from the start. If it finds a number on the first level, it puts it on the first shelf. If the branch goes deeper, it puts that number on a lower shelf.
Once all the branches have been visited, the shelves are organized from top to bottom. Since the goal is to show the bottom parts of the tree first, the code turns the shelves upside down so the deepest ones are at the start and the top ones are at the end. It is much like taking a stack of blocks and flipping the whole tower so the bottom blocks end up on top.
Code Quality
Complexity Analysis
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++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | JS | Rust | Java | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| DimitrisJim | JS | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lennylxx | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| DimitrisJim | JavaScript | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lennylxx | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 102: Binary Tree Level Order Traversal
- problem 637: Average of Levels in Binary Tree
Solved On The Same Day
- problem 110: Balanced Binary Tree
- problem 111: Minimum Depth of Binary Tree
- problem 118: Pascal's Triangle
- problem 119: Pascal's Triangle II
- problem 228: Summary Ranges
- problem 530: Minimum Absolute Difference in BST
- problem 82: Remove Duplicates from Sorted List II
- problem 102: Binary Tree Level Order Traversal
- problem 103: Binary Tree Zigzag Level Order Traversal
- problem 105: Construct Binary Tree from Preorder and Inorder Traversal
- problem 106: Construct Binary Tree from Inorder and Postorder Traversal
- problem 109: Convert Sorted List to Binary Search Tree
- problem 117: Populating Next Right Pointers in Each Node II
- problem 128: Longest Consecutive Sequence
- problem 138: Copy List with Random Pointer
- problem 150: Evaluate Reverse Polish Notation
- problem 155: Min Stack
- problem 209: Minimum Size Subarray Sum
- problem 274: H-Index
- problem 380: Insert Delete GetRandom O(1)
- problem 427: Construct Quad Tree
- problem 452: Minimum Number of Arrows to Burst Balloons
- problem 30: Substring with Concatenation of All Words
- problem 37: Sudoku Solver
- problem 44: Wildcard Matching
- problem 1326: Minimum Number of Taps to Open to Water a Garden
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