Algo-Sim › Binary Trees & BST

Inorder Traversal (Iterative)

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

Inorder with an explicit stack: push the whole left spine, pop and output, then move to the right child.

Problem

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

Constraints

Edge cases to test

Follow-up questions

Why is it O(h) space?
The stack only holds the current left spine, at most the tree’s height.
How do you walk in reverse order?
Swap the roles of left and right: descending order in a BST.
Can you do it in O(1) extra space?
Morris traversal: thread each inorder predecessor’s empty right pointer back to its node, follow it up, then remove it. O(n) time, O(1) space, and the tree is restored.

Solution

Java

public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> out = new ArrayList<>();
    Deque<TreeNode> stack = new ArrayDeque<>();
    TreeNode curr = root;
    while (curr != null || !stack.isEmpty()) {
        while (curr != null) {
            stack.push(curr);
            curr = curr.left;
        }
        curr = stack.pop();
        out.add(curr.val);
        curr = curr.right;
    }
    return out;
}

Python

def inorder_traversal(root):
    out, stack = [], []
    curr = root
    while curr or stack:
        while curr:
            stack.append(curr)
            curr = curr.left
        curr = stack.pop()
        out.append(curr.val)
        curr = curr.right
    return out

C++

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

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

More Binary Trees & BST problems