Binary Tree Postorder Traversal

Pattern: Traversals

easy

Postorder visits left, right, then the node. A neat iterative way: do 'node, right, left' (preorder with the pushes swapped) and reverse the list at the end.

The problem

Return the postorder traversal of a binary tree: left subtree, right subtree, node. [1, null, 2, 3] gives [3, 2, 1]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • What is postorder read backwards?
  • Which traversal is easy to write and gives 'node, right, left'?
  • What is left to do?

Hints

    Brute force, and why it fails

    Recursion: visit(left); visit(right); record. A one-stack iterative version that tracks the last visited node also works but is fiddly.

    The key insight

    Reversing 'node, right, left' gives 'left, right, node', so a mirrored preorder plus a reversal is postorder.

    Dry run

    order1

    root = [1, null, 2, 3]. Pop 1, record, push its child 2.

    Step 1 of 3

    The plan

    stack = [root]
    while stack:
        n = pop; record n
        push n.left if any; push n.right if any
    reverse the record
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Each node is handled once; the output is reversed at the end.

    Edge cases

    • Empty tree: an empty list.
    • One node.
    • A tree that is a single long chain: the stack grows to n.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> postorderTraversal(TreeNode root) {
            LinkedList<Integer> out = new LinkedList<>();
            if (root == null) return out;
            Deque<TreeNode> stack = new ArrayDeque<>();
            stack.push(root);
            while (!stack.isEmpty()) {              // node, right, left ... then reversed gives left, right, node
                TreeNode node = stack.pop();
                out.addFirst(node.val);
                if (node.left != null) stack.push(node.left);
                if (node.right != null) stack.push(node.right);
            }
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<int> postorderTraversal(TreeNode* root) {
            vector<int> out;
            if (root == NULL) return out;
            stack<TreeNode*> st;
            st.push(root);
            while (!st.empty()) {                   // node, right, left ... then reversed gives left, right, node
                TreeNode* node = st.top();
                st.pop();
                out.push_back(node->val);
                if (node->left != NULL) st.push(node->left);
                if (node->right != NULL) st.push(node->right);
            }
            reverse(out.begin(), out.end());
            return out;
        }
    };

    Python

    class Solution:
        def postorderTraversal(self, root) -> list[int]:
            out, stack = [], [root] if root else []
            while stack:                            # node, right, left ... then reversed gives left, right, node
                node = stack.pop()
                out.append(node.val)
                if node.left:
                    stack.append(node.left)
                if node.right:
                    stack.append(node.right)
            return out[::-1]

    Common mistakes

    • Forgetting the reversal.
    • Pushing right before left, which gives the wrong order after reversing.

    Similar problems