Algo-Sim › Binary Trees & BST

Preorder Traversal (Iterative)

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

Preorder with an explicit stack: pop a node, output it, push right then left so left comes off first.

Problem

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

Constraints

Edge cases to test

Follow-up questions

Why push right before left?
A stack pops the last push first, so pushing right first makes left come off next.
Can you do it in O(1) space?
Morris traversal threads each node’s inorder predecessor back to it and removes the thread afterwards: O(n) time, O(1) space.

Solution

Java

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

Python

def preorder_traversal(root):
    out = []
    stack = [root] if root else []
    while stack:
        node = stack.pop()
        out.append(node.val)
        if node.right:
            stack.append(node.right)
        if node.left:
            stack.append(node.left)
    return out

C++

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

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

More Binary Trees & BST problems