Algo-Sim › Binary Trees & BST

Postorder Traversal (Iterative)

Easy · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Postorder with one stack and a last-output pointer: output a node only after its right subtree is finished.

Problem

Return a binary tree's postorder traversal (left, right, node) without recursion, using one explicit stack.

Constraints

Edge cases to test

Follow-up questions

What is the two-stack trick?
Do a modified preorder (node, right, left) and reverse the output: simpler, but O(n) extra.
Why track the last node output?
It tells a parent on top of the stack whether its right subtree is done or still needs a visit.

Solution

Java

public List<Integer> postorderTraversal(TreeNode root) {
    List<Integer> out = new ArrayList<>();
    Deque<TreeNode> stack = new ArrayDeque<>();
    TreeNode curr = root, last = null;
    while (curr != null || !stack.isEmpty()) {
        while (curr != null) {
            stack.push(curr);
            curr = curr.left;
        }
        TreeNode top = stack.peek();
        if (top.right != null && top.right != last) {
            curr = top.right;
        } else {
            out.add(top.val);
            last = stack.pop();
        }
    }
    return out;
}

Python

def postorder_traversal(root):
    out, stack = [], []
    curr, last = root, None
    while curr or stack:
        while curr:
            stack.append(curr)
            curr = curr.left
        top = stack[-1]
        if top.right and top.right is not last:
            curr = top.right
        else:
            out.append(top.val)
            last = stack.pop()
    return out

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> out = {};
        deque<TreeNode *> stack = {};
        TreeNode *curr = root, *last = nullptr;
        while (curr != nullptr || !stack.empty()) {
            while (curr != nullptr) {
                stack.push_back(curr);
                curr = curr->left;
            }
            TreeNode *top = stack.back();
            if (top->right != nullptr && top->right != last) {
                curr = top->right;
            } else {
                out.push_back(top->val);
                last = stack.back();
                stack.pop_back();
            }
        }
        return out;
    }
};

More Binary Trees & BST problems