AlgoInsight

DSA problem

Binary Tree Postorder Traversal

EasyTree Traversal - Post-OrderPattern: Tree Traversal - Post-Ordertop75FreeAmazonMicrosoftGoogleMetaApple

Given the root of a binary tree, return the postorder traversal of its nodes' values. Postorder visits each node in the order left subtree → right subtree → root, so the root is always the last value emitted, preceded by the full left subtree and then the full right subtree, each recursively in postorder.

Postorder is the natural traversal whenever you want to process a node after both of its children have already been processed. It is the cornerstone of bottom-up tree algorithms: computing subtree heights, deleting a tree, evaluating postfix expressions, or any problem where the parent's answer depends on aggregating results from the children. Almost every "return information up the tree" pattern is structurally a postorder traversal.

The recursive solution is a textbook three-liner: recurse left, recurse right, then visit the current node. It is clean and obvious, but it consumes O(h) stack frames where h is the height of the tree, which degrades to O(n) for a skewed tree.

The iterative solution is the interesting one. A clean trick is to perform a modified preorder in the order root → right → left (a mirror of true preorder), then reverse the result — what you collected as "root, right, left" reverses into "left, right, root", exactly postorder. Below we show that approach because it uses a single explicit stack and avoids the "last visited" bookkeeping that a literal iterative postorder requires. Both forms run in O(n) time; the reverse-mirror form is the cleanest iterative version you can write under interview pressure.

Examples

Example 1
Input: root = [1,null,2,3]
Output: [3,2,1]
Explanation: Left subtree of root 1 is empty; right subtree rooted at 2 has left child 3. Postorder visits 3, then 2, then root 1.
Example 2
Input: root = []
Output: []
Explanation: An empty tree produces an empty traversal.
Example 3
Input: root = [1,2,3,4,5,null,6]
Output: [4,5,2,6,3,1]
Explanation: Left subtree rooted at 2 yields [4,5,2]; right subtree rooted at 3 yields [6,3]; finally the root 1 is appended.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

treebinary-treestackdepth-first-searchpostorder

Browse all DSA problems