15% off all plans & roadmaps Use code
See plansBinary Tree Postorder Traversal
- LeetCode 145
- Easy
- Tree Traversal Patterns (DFS & BFS)
- Recursive Postorder Traversal
Updated
TL;DR: You must return the values of a binary tree in postorder, which means left subtree, right subtree, then the node. Recurse into both children and record the node last, or use an explicit stack and reverse the output.
Problem
Given the root of a binary tree, return the postorder traversal of its nodes' values.
Example 1
Input: root = [1,null,2,3] Output: [3,2,1]
Example 2
Input: root = [1,2,3,4,5,null,8,null,null,6,7,9] Output: [4,6,7,5,2,9,8,3,1]
Example 3
Input: root = [] Output: []
Example 4
Input: root = [1] Output: [1]
Constraints
- The number of nodes in the tree is in the range
[0, 100]. -100 <= Node.val <= 100
Constraints that matter
- The tree has at most 100 nodes, so recursion depth is at most 100. Recursion is safe here, but a 10^5-node chain would overflow the call stack.
- n up to 100 does not rule out the O(n^2) concatenation, so you must argue with growth rate, not with timing on small inputs.
- Node values range from -100 to 100, but the solution never uses values as keys or indexes. Do not build a counting array.
- The root can be null. The empty input must return an empty list, so every approach needs a null base case.
Hints
Hint 1
This problem asks for a fixed visiting order.
Hint 2
Write the definition as code.
Solution
Intuition
This problem asks for a fixed visiting order. Every value must appear after all values in its left and right subtrees, and before nothing else in that subtree. A depth-first walk that records the node after both child calls return produces exactly that order.
Picture a pile of order slips where you take the top slip, write its name on a sheet, and place its children's slips on top. The pile is the explicit stack, the sheet is the out list, and reading the sheet bottom to top gives postorder.
To recognise it, look at what the answer depends on. The position of a node in the output depends on the subtrees below it, not on the nodes above it. So you process the children first and append the parent last. This is the Tree DFS pattern with postorder ordering.
A recursive call returns only after its whole subtree is done. A subtree's values therefore form one contiguous block in the output, and the subtree's root closes that block. Each node is recorded once, at the moment its subtree is finished.
Worked example
Input: root = [1, 2, 3, 4, 5, null, 8, null, null, 6, 7, 9] Output: [4, 6, 7, 5, 2, 9, 8, 3, 1] Explanation: The level-order array builds the tree 1(2(4, 5(6, 7)), 3(null, 8(9, null))). Postorder visits the left subtree, then the right subtree, then the node. So 4 comes first, then 5's subtree (6, 7, 5), then 2. Node 3 comes after the subtree of 8 (9, 8), and the root 1 comes last.
Approach 1: Brute force: concatenate child lists
Write the definition as code. The postorder list of a node is the postorder list of its left child, then the postorder list of its right child, then the node's value. Each call returns a new list, and the parent joins the two child lists onto its own value.
This is correct, but joining lists copies data. A node at depth d is copied once by each of its d ancestors. On a chain of n nodes, the copying adds up to roughly n^2 / 2 element moves.
Steps
- If the node is null, return an empty list.
- Recursively get the postorder list of
node.left. - Recursively get the postorder list of
node.right. - Build a new list with the left values, then the right values, then
node.val. - Return the new list to the parent call.
Dry run
Trace the example tree. The leaves return one-element lists: 4 gives [4], 6 gives [6], 7 gives [7], and 9 gives [9]. Node 5 joins [6] and [7] and its value, giving [6, 7, 5]. Node 2 joins [4] and [6, 7, 5], then adds 2, giving [4, 6, 7, 5, 2].
Node 8 gives [9, 8], and node 3 gives [9, 8, 3] because its left child is null. The root joins [4, 6, 7, 5, 2] with [9, 8, 3] and adds 1. The result is [4, 6, 7, 5, 2, 9, 8, 3, 1].
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(n^2) allocated in total |
Let n be the number of nodes. Each node's value is copied once for every ancestor, because each ancestor builds a new list from its children's lists. On a chain of n nodes the depths are 0 through n - 1, so the copies sum to n(n - 1) / 2, which is O(n^2). Each copy allocates memory, so the total allocated space is also O(n^2).
PythonTested in our runner
from typing import List, Optional
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return []
# Copy both child lists, then add this node's value
return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val]JavaTested in our runner
import java.util.*;
class Solution {
public int[] postorderTraversal(TreeNode root) {
List<Integer> values = build(root);
int[] out = new int[values.size()];
for (int i = 0; i < out.length; i++) {
out[i] = values.get(i);
}
return out;
}
// Returns a new list for every subtree, which is the costly part
private List<Integer> build(TreeNode node) {
List<Integer> res = new ArrayList<>();
if (node == null) {
return res;
}
res.addAll(build(node.left));
res.addAll(build(node.right));
res.add(node.val);
return res;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
if (root == nullptr) {
return {};
}
vector<int> res = postorderTraversal(root->left);
vector<int> right = postorderTraversal(root->right);
res.insert(res.end(), right.begin(), right.end());
res.push_back(root->val);
return res;
}
};JavaScriptTested in our runner
var postorderTraversal = function(root) {
if (!root) {
return [];
}
const left = postorderTraversal(root.left);
const right = postorderTraversal(root.right);
return [...left, ...right, root.val];
};GoTested in our runner
func postorderTraversal(root *TreeNode) []int {
if root == nil {
return []int{}
}
left := postorderTraversal(root.Left)
right := postorderTraversal(root.Right)
res := make([]int, 0, len(left)+len(right)+1)
res = append(res, left...)
res = append(res, right...)
res = append(res, root.Val)
return res
}C#Tested in our runner
public class Solution {
public int[] postorderTraversal(TreeNode root) {
if (root == null) {
return new int[0];
}
int[] left = postorderTraversal(root.left);
int[] right = postorderTraversal(root.right);
int[] res = new int[left.Length + right.Length + 1];
left.CopyTo(res, 0);
right.CopyTo(res, left.Length);
res[res.Length - 1] = root.val;
return res;
}
}The Recursive Postorder Traversal infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Recursive Postorder Traversal
Approach 2: Recursion with one shared listRecursive Postorder Traversal
What is slow in the first approach is the copying. The output order is the order in which the recursion finishes each node, so you can build the answer in one list in that same order. Pass the same list down the recursion, and append a node's value after both recursive calls return.
This removes all copying. Each node is appended exactly once, and each call does constant work besides its two recursive calls.
Steps
- Create one empty list
resultoutside the recursion. - Write
traverse(node). Ifnodeis null, return. - Call
traverse(node.left), thentraverse(node.right). - Append
node.valtoresult. - Call
traverse(root)and returnresult.
Dry run
Trace the example tree. Going down the left side, the calls reach 4 first. Node 4 has no children, so 4 is appended. Back at 2, the walk goes right into 5, which goes into 6.
Node 6 is appended, then 7, then 5 after both children. Node 2 is appended when its right side is done. Back at the root, the walk goes into 3, which has no left child, then into 8.
Node 9 is appended, then 8, then 3, and finally the root 1. The list is [4, 6, 7, 5, 2, 9, 8, 3, 1].
Complexity
| Time | O(n) |
|---|---|
| Space | O(h) for the call stack |
Let n be the number of nodes and h the height of the tree. Each node causes one call to traverse and one append, and each call does constant work apart from its children. That gives O(n) time. The call stack holds one frame per node on the current path, so it reaches h frames, which is O(n) on a skewed tree and O(log n) on a balanced one.
PythonTested in our runner
from typing import List, Optional
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
result = []
def traverse(node):
if node is None:
return
traverse(node.left)
traverse(node.right)
result.append(node.val)
traverse(root)
return resultJavaTested in our runner
import java.util.*;
class Solution {
public int[] postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
traverse(root, result);
int[] out = new int[result.size()];
for (int i = 0; i < out.length; i++) {
out[i] = result.get(i);
}
return out;
}
private void traverse(TreeNode node, List<Integer> result) {
if (node == null) {
return;
}
traverse(node.left, result);
traverse(node.right, result);
result.add(node.val);
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
traverse(root, result);
return result;
}
private:
void traverse(TreeNode* node, vector<int>& result) {
if (node == nullptr) {
return;
}
traverse(node->left, result);
traverse(node->right, result);
result.push_back(node->val);
}
};JavaScriptTested in our runner
var postorderTraversal = function(root) {
const result = [];
const traverse = (node) => {
if (!node) {
return;
}
traverse(node.left);
traverse(node.right);
result.push(node.val);
};
traverse(root);
return result;
};GoTested in our runner
func postorderTraversal(root *TreeNode) []int {
result := []int{}
var traverse func(node *TreeNode)
traverse = func(node *TreeNode) {
if node == nil {
return
}
traverse(node.Left)
traverse(node.Right)
result = append(result, node.Val)
}
traverse(root)
return result
}C#Tested in our runner
public class Solution {
public int[] postorderTraversal(TreeNode root) {
List<int> result = new List<int>();
Traverse(root, result);
return result.ToArray();
}
private void Traverse(TreeNode node, List<int> result) {
if (node == null) {
return;
}
Traverse(node.left, result);
Traverse(node.right, result);
result.Add(node.val);
}
}Approach 3: Iterative with explicit stack, then reverseOptimal
Recursion uses the call stack, which the follow-up asks you to replace. Reverse postorder is root, then right subtree, then left subtree. That order is easy to produce with a stack. Pop a node, record it, then push its left and right children.
Because the right child is pushed last, it is popped first, so the right side is recorded before the left side. Reverse the recorded list at the end. Root, right, left, read backwards, is left, right, root. The time is O(n), and the only extra memory is the stack.
Why it is correct. Each node is popped only after its parent, so the parent is written before all of its descendants. The right child is pushed after the left, so the right subtree is written before the left subtree. Reversing that root, right, left sequence turns every subtree into a contiguous block that ends at its root, which is postorder.
Steps
- If the root is null, return an empty list.
- Push the root onto a stack.
- Pop a node and append its value to
out. - Push its left child if it exists, then its right child if it exists.
- Repeat until the stack is empty, then reverse
outand return it.
Dry run
The table traces the example tree. Each row shows the stack after one pop and its pushes, with the top on the right. The last row is the output before reversing.
| Step | Stack after step (top on right) | Popped node | Output so far |
|---|---|---|---|
| 0 | [1] | none | [] |
| 1 | [2, 3] | 1 | [1] |
| 2 | [2, 8] | 3 | [1, 3] |
| 3 | [2, 9] | 8 | [1, 3, 8] |
| 4 | [2] | 9 | [1, 3, 8, 9] |
| 5 | [4, 5] | 2 | [1, 3, 8, 9, 2] |
| 6 | [4, 6, 7] | 5 | [1, 3, 8, 9, 2, 5] |
| 7 | [4, 6] | 7 | [1, 3, 8, 9, 2, 5, 7] |
| 8 | [4] | 6 | [1, 3, 8, 9, 2, 5, 7, 6] |
| 9 | [] | 4 | [1, 3, 8, 9, 2, 5, 7, 6, 4] |
Reversing the last output gives [4, 6, 7, 5, 2, 9, 8, 3, 1], which matches the expected answer.
Complexity
| Time | O(n) |
|---|---|
| Space | O(h) for the stack, O(n) in the worst case |
Let n be the number of nodes. Each node is pushed once and popped once, and each pop does constant work, so the loop is O(n). The final reverse makes one more pass over the n values. The stack holds the pending left siblings along the current path plus at most two children of the node being processed, so its size is O(h), which is O(n) in the worst case.
PythonTested in our runner
from typing import List, Optional
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return []
stack = [root]
out = []
while stack:
node = stack.pop()
out.append(node.val)
# Push left first so right is popped first
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
# The output is root, right, left. Reverse it.
out.reverse()
return outJavaTested in our runner
import java.util.*;
class Solution {
public int[] postorderTraversal(TreeNode root) {
if (root == null) {
return new int[0];
}
List<Integer> out = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
out.add(node.val);
if (node.left != null) {
stack.push(node.left);
}
if (node.right != null) {
stack.push(node.right);
}
}
// The output is root, right, left. Reverse it.
int n = out.size();
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = out.get(n - 1 - i);
}
return res;
}
}C++Tested in our runner
#include <stack>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> out;
if (root == nullptr) {
return out;
}
stack<TreeNode*> st;
st.push(root);
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
out.push_back(node->val);
if (node->left != nullptr) {
st.push(node->left);
}
if (node->right != nullptr) {
st.push(node->right);
}
}
// The output is root, right, left. Reverse it.
reverse(out.begin(), out.end());
return out;
}
};JavaScriptTested in our runner
var postorderTraversal = function(root) {
const out = [];
if (!root) {
return out;
}
const stack = [root];
while (stack.length > 0) {
const node = stack.pop();
out.push(node.val);
if (node.left) {
stack.push(node.left);
}
if (node.right) {
stack.push(node.right);
}
}
// The output is root, right, left. Reverse it.
return out.reverse();
};GoTested in our runner
func postorderTraversal(root *TreeNode) []int {
out := []int{}
if root == nil {
return out
}
stack := []*TreeNode{root}
for len(stack) > 0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
out = append(out, node.Val)
if node.Left != nil {
stack = append(stack, node.Left)
}
if node.Right != nil {
stack = append(stack, node.Right)
}
}
for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {
out[i], out[j] = out[j], out[i]
}
return out
}C#Tested in our runner
public class Solution {
public int[] postorderTraversal(TreeNode root) {
if (root == null) {
return new int[0];
}
List<int> output = new List<int>();
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.Push(root);
while (stack.Count > 0) {
TreeNode node = stack.Pop();
output.Add(node.val);
if (node.left != null) {
stack.Push(node.left);
}
if (node.right != null) {
stack.Push(node.right);
}
}
// The output is root, right, left. Reverse it.
output.Reverse();
return output.ToArray();
}
}Common mistakes
result.append(node.val)placed before the two recursive calls. This gives root-first order. Move the append after bothtraverse(node.left)andtraverse(node.right)return.traverse(node.left, new ArrayList<>())creates a fresh list for each call. The values vanish when the call returns. Pass the same shared list into every call.traverse(node.left)called on a null node, ornode.leftread whennodeis null. Check for null at the top oftraversebefore touching any field.stack.push(node.right)beforestack.push(node.left)in the iterative version. Popping then gives root, left, right, and the reversed output is wrong. Push left first, then right.- Skipping the final reverse in the iterative version. Without it the output is root, right, left, which is the reversed postorder.
- Returning a
List<Integer>from the public method in Java or C#, where the starter needsint[]. Build the list inside helpers and convert to an array only at the top level.
Edge cases
root = [](null root): return an empty list. The iterative version must check for null before pushing, because the loop would readnode.valon a null node.root = [1]: a single node returns[1]. The reverse step leaves a one-element list unchanged.- A left-leaning chain 1 -> 2 -> 3 (only left children): returns
[3, 2, 1]. A right-leaning chain 1 -> 2 -> 3 also returns[3, 2, 1], because the order depends on position, not on which side is longer. - Negative and repeated values: a root of -1 with left child -2 and right child -1 returns
[-2, -1, -1]. Nodes are placed by tree position, so equal values are never merged or reordered by value. - Maximum size of 100 nodes in a chain: the recursion depth is 100, which is well within the default call stack in all six languages.
Follow-ups interviewers ask
- How do you remove the call stack from the recursive solution?
- Use an explicit stack. Pop a node, record it, push its left child, then push its right child. Reverse the recorded list at the end. The time stays O(n), and the stack size stays O(h). This is the third approach on this page.
- Can you traverse with O(1) extra space, not counting the output?
- Yes, with Morris-style threading. You temporarily point the rightmost node of each left subtree back to its ancestor, walk the tree, and undo those links. The time is O(n) and the extra space is O(1). The code is error prone, so use it only when stack memory is the stated limit.
- What if the tree is too large to hold the whole result in memory?
- The reverse trick needs the full output before it can emit anything. To stream values, push each node twice, once unvisited and once marked as ready to emit, and emit a node when its second copy is popped. Memory is O(h) plus the stack of marked nodes, and values come out in postorder as they are ready.
Binary Tree Postorder Traversal FAQ
What is the time complexity of Binary Tree Postorder Traversal?
The recursive-with-shared-list and iterative solutions run in O(n) time, where n is the number of nodes. Each node is visited once and does constant work. The list concatenation approach is O(n^2) on a skewed tree because it copies data at every level.
Why use depth-first recursion for Binary Tree Postorder Traversal?
Postorder means children before the node. A recursive call returns only after its whole subtree is processed, so appending after the two calls produces the right order. The explicit stack version does the same job without the call stack.
Can Binary Tree Postorder Traversal be solved in O(1) extra space?
Not with a plain stack, which needs O(h) space, and h can be n on a skewed tree. Morris-style traversal reaches O(1) extra space by threading temporary pointers through the tree and restoring them afterward. It still runs in O(n) time but is harder to write correctly.
Why does the iterative postorder solution reverse its output?
Pushing left first and popping gives root, then right side, then left side. That is postorder read backwards. Reversing the list fixes the order in one O(n) pass.
What is the difference between preorder and postorder traversal?
Preorder records the node before its children, so the root comes first. Postorder records the node after both children, so the root comes last. The code differs only in where the append sits.
Asked at
See which companies ask this — Pro
Related problems
- Balanced Binary Tree · same technique: Recursive Postorder Traversal
- Diameter of Binary Tree · same technique: Recursive Postorder Traversal
- Maximum Depth of Binary Tree · same technique: Recursive Postorder Traversal
- House Robber III · same technique: Recursive Postorder Traversal
- Delete Leaves With a Given Value · same technique: Recursive Postorder Traversal
- Same Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Invert Binary Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Subtree of Another Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Binary Tree Inorder Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)
- Binary Tree Preorder Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)