Problem 145

Abstract / Summary

Given the root of a binary tree return the sequence of its nodes values in postorder traversal order.

Note

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

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)
9 lines | 300 bytes | submitted September 1, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 79% (2+ million submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Depth First Search
  • Stack
  • 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 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:

  1. Recurse into the left child.
  2. Recurse into the right child.
  3. 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.

written by openai gpt

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.

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 = 8 | μ = 7.41 | σ = 1.71

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++ 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++
63 links | 48 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'LeetCode 145. Binary Tree Postorder Traversal RECURSIVELY - Interview Prep Ep 68'
Fisher Coder 8 mins
LeetCode 145. Binary Tree Postorder Traversal RECURSIVELY - Interview Prep Ep 68
YouTube video '[Java] Leetcode 145. Binary Tree Postorder Traversal (Iteratively & Recursively) [Binary Tree #3]'
Eric Programming 19 mins
[Java] Leetcode 145. Binary Tree Postorder Traversal (Iteratively & Recursively) [Binary Tree #3]
YouTube video 'Post-order traversal of Binary Tree | Step by step demo with example | Study Algorithms'
Nikhil Lohia 10 mins
Post-order traversal of Binary Tree | Step by step demo with example | Study Algorithms
YouTube video 'LeetCode 145 Binary Tree Postorder Traversal iterative'
leetuition 11 mins
LeetCode 145 Binary Tree Postorder Traversal iterative
YouTube video '889. Construct Binary Tree from Preorder and Postorder Traversal | leetcode daily challenge | dsa'
ShashCode 17 mins
889. Construct Binary Tree from Preorder and Postorder Traversal | leetcode daily challenge | dsa
YouTube video 'Binary Tree Preorder Inorder Postorder Traversal Iterative Implementation'
happygirlzt 13 mins
Binary Tree Preorder Inorder Postorder Traversal Iterative Implementation
YouTube video 'Leetcode 145. Binary Tree Postorder Traversal'
NeedCode⚡ 8 mins
Leetcode 145. Binary Tree Postorder Traversal
YouTube video '145. Binary Tree Postorder Traversal - Java Solution'
Code with Carter 8 mins
145. Binary Tree Postorder Traversal - Java Solution
YouTube video '145. Binary Tree Postorder Traversal - Recursive'
Persistent Programmer 7 mins
145. Binary Tree Postorder Traversal - Recursive
YouTube video '145. Binary Tree Postorder Traversal || Java || Leetcode || Hindi'
Coding Sphere 4 mins
145. Binary Tree Postorder Traversal || Java || Leetcode || Hindi
YouTube video 'Leetcode | 145. Binary Tree Postorder Traversal | Easy | Java Solution'
Developer Docs 4 mins
Leetcode | 145. Binary Tree Postorder Traversal | Easy | Java Solution
YouTube video '145 Binary tree postorder traversal leetcode problem in c++|leetcode for beginners|leetcode solution'
Coding enthusiast 4 mins
145 Binary tree postorder traversal leetcode problem in c++|leetcode for beginners|leetcode solution
YouTube video 'Binary Tree Postorder Traversal Made Super Easy! - leetcode 145'
CodingNinja 11 mins
Binary Tree Postorder Traversal Made Super Easy! - leetcode 145
YouTube video 'Daily Leetcode #1608: Aug 25, 2024 - 145. Binary Tree Postorder Traversal'
Programming Live with Larry 13 mins
Daily Leetcode #1608: Aug 25, 2024 - 145. Binary Tree Postorder Traversal
YouTube video 'How To Solve "145  Binary Tree Postorder Traversal" on LeetCode - JavaScript'
Becoming A Better Dev (with David) 5 mins
How To Solve "145 Binary Tree Postorder Traversal" on LeetCode - JavaScript
YouTube video 'Binary Tree Postorder Traversal - Google Interview Questions - LeetCode 145 Solution - C++'
nexTRIE 3 mins
Binary Tree Postorder Traversal - Google Interview Questions - LeetCode 145 Solution - C++
YouTube video '145. Binary Tree Postorder Traversal | Leetcode | Python'
Abdullah Arshed 7 mins
145. Binary Tree Postorder Traversal | Leetcode | Python
YouTube video '145. Binary Tree Postorder Traversal | Java | Leetcode | Binary Tree | DSA'
Coding with Tamilarasan 17 mins
145. Binary Tree Postorder Traversal | Java | Leetcode | Binary Tree | DSA
YouTube video 'LeetCode 145 - Binary Tree Postorder Traversal - Java'
Alpha-Code 16 mins
LeetCode 145 - Binary Tree Postorder Traversal - Java
YouTube video 'Leetcode 145. Binary Tree Postorder Traversal - iterative method with stack'
Code-Yao 10 mins
Leetcode 145. Binary Tree Postorder Traversal - iterative method with stack
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

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