Python 0145.py
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
def deeper(node):
if node:
yield from deeper(node.left)
yield from deeper(node.right)
yield node.val
yield from deeper(root)
Difficulty
and has an acceptance rate of about 79% (2+ million submissions).
Typical patterns to solve this problem:
- Binary Tree
- Depth First Search
- Stack
- 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 public method postorderTraversal. The method returns an iterator that produces the values of a binary tree in post-order (left subtree, right subtree, node). The core of the algorithm is a nested generator function named deeper that recursively walks the tree and yields node values in the required order. By delegating the iteration to the generator, the solution delivers results lazily, which can be advantageous when only a portion of the traversal is needed.
Core Logic
The public method simply forwards the traversal to the inner generator:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
def deeper(node):
if node:
yield from deeper(node.left)
yield from deeper(node.right)
yield node.val
yield from deeper(root)
The deeper function embodies the three essential steps of a post-order traversal:
- Recurse into the left child.
- Recurse into the right child.
- Yield the current node’s value.
Each step is expressed with a yield from statement, which transparently forwards all values produced by the recursive call to the caller of deeper. The final yield node.val supplies the value of the current node after its subtrees have been exhausted.
Edge-Case Handling
When the input tree is empty (root is None), the outer yield from deeper(root) invokes deeper with a None argument. Inside deeper, the guard if node: fails, causing the function to return without yielding any values. Consequently, the caller receives an empty iterator, which matches the expected result for an empty tree.
The recursive structure also gracefully handles trees that consist of a single node. In that scenario, the left and right recursive calls both receive None and produce no output, after which the solitary node’s value is yielded.
Performance Characteristics
The algorithm leverages Python’s generator protocol to produce values on demand. This lazy evaluation means that the traversal does not allocate a list containing all node values up front; memory consumption grows only with the depth of the recursion stack, not with the total number of nodes. For large trees, this can lead to a substantially lower memory footprint compared to an implementation that builds a full list before returning.
The use of yield from eliminates the need for explicit loops to concatenate results from sub-calls. By directly delegating to the child generators, the code avoids the overhead of constructing intermediate collections, which contributes to a more streamlined execution path.
Because the traversal is depth-first, the call stack depth at any moment equals the height of the tree. The implementation does not introduce any auxiliary data structures such as explicit stacks or queues, keeping the runtime overhead minimal and the code concise.
ELI5 - Simplified Explanation
Imagine a giant tree standing upside down, where every branch has a little box with a number inside. The goal is to visit every single box to see what is written inside.
To do this, there is a special explorer who starts at the very top of the tree. The explorer follows a specific rule to make sure no box is missed. First, the explorer crawls down all the way to the leftmost branch to find the boxes hidden there. After checking the left side, the explorer goes over to the right side to visit all those boxes. Finally, the explorer looks at the box right in front of them.
This happens over and over again as the explorer moves through the branches. By doing this in the same order every time, the explorer collects all the numbers starting from the bottom left, moving across to the right, and finishing at the very top. It is like a treasure hunt where the rule is to always look at the side branches before grabbing the gift at the center of the fork.
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++ | Python | Java | TS | ||||||||
| WalkCCC | C++ | Python | Java | ||||||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | |||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | AdelDaniel | Dart | |||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| black-shadows | C++ | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| Dijkstra-Edu | Java | ||||||||||||
| DimitrisJim | C | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fpdjsns | Python | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| gouthampradhan | Java | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| Krazune | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++ | ||||||||||||
| muhammadfarhankt | Go | ||||||||||||
| pruthvikp | Python | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| Shamik07 | Dart | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| 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 | ||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| AdelDaniel | Dart | ||||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| Dijkstra-Edu | Java | ||||||||||||
| DimitrisJim | C | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fpdjsns | Python | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| gouthampradhan | Java | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| Krazune | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++ | ||||||||||||
| muhammadfarhankt | Go | ||||||||||||
| pruthvikp | Python | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| Shamik07 | Dart | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 94: Binary Tree Inorder Traversal
- problem 2477: Minimum Fuel Cost to Report to the Capital
Solved On The Same Day
- problem 144: Binary Tree Preorder 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 513: Find Bottom Left Tree Value
- 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