Binary Tree Postorder Traversal
LeetCode 145 · Easy · solution, intuition & step-by-step walkthrough
Left → right → node.
This is how I solved Binary Tree Postorder Traversal (LeetCode 145), an easy problem from the Traversals (Recursive / Iterative) pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Post-order visits both children before the node itself — the order you'd use to delete a tree or combine child results.
Approach
- 1
dfs(None) returns.
- 2
dfs(left), dfs(right), then record node.val.
How I solved it
Recursive DFSPythonO(n) time · O(h) space
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
def dfs(node):
if node==None:
return None
dfs(node.left)
dfs(node.right)
res.append(node.val)
dfs(root)
return resBinary Tree Postorder Traversal — FAQ
What is the intuition behind Binary Tree Postorder Traversal?
Post-order visits both children before the node itself — the order you'd use to delete a tree or combine child results.
How do you solve Binary Tree Postorder Traversal (LeetCode 145)?
1. dfs(None) returns. 2. dfs(left), dfs(right), then record node.val.
What is the time and space complexity of Binary Tree Postorder Traversal?
Time: O(n). Space: O(h). (Accepted approach: Recursive DFS.)
What are common mistakes in Binary Tree Postorder Traversal?
Iterative post-order is the trickiest of the three — reversed (node, right, left) is a neat shortcut.