Problem 107

Abstract / Summary

Return the levels of a binary tree from bottom to top with nodes in each level from left to right.

Note

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

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()) ])
14 lines | 462 bytes | submitted August 31, 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 69% (1+ million submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Breadth 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 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.

written by openai gpt

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.

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.48 | σ = 1.40

Complexity Analysis

not analyzed yet

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++ 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++
56 links | 40 authors | 11 languages

Videos

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

Similar Problems

2 similar problems

Solved On The Same Day

27 solutions   August 31, 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