Binary Tree Preorder Traversal

Pattern: Traversals

easy

Preorder visits the node, then the left subtree, then the right. Iteratively: pop a node from a stack, record it, and push its right child and then its left, so the left is handled first.

The problem

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

Think first

  • Which node comes first?
  • Which child must come out of the stack first?
  • So in what order do you push them?

Hints

    Brute force, and why it fails

    Recursion: record; visit(left); visit(right).

    The key insight

    A stack gives back the most recent push, so pushing right before left makes the left subtree finish before the right one starts.

    Dry run

    stack2
    out1

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

    Step 1 of 3

    The plan

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

    Complexity

    Time
    O(n)
    Space
    O(h)

    Each node is pushed and popped once.

    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> preorderTraversal(TreeNode root) {
            List<Integer> out = new ArrayList<>();
            if (root == null) return out;
            Deque<TreeNode> stack = new ArrayDeque<>();
            stack.push(root);
            while (!stack.isEmpty()) {
                TreeNode node = stack.pop();
                out.add(node.val);                  // visit the node first
                if (node.right != null) stack.push(node.right);   // push right first so left comes out first
                if (node.left != null) stack.push(node.left);
            }
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode* root) {
            vector<int> out;
            if (root == NULL) return out;
            stack<TreeNode*> st;
            st.push(root);
            while (!st.empty()) {
                TreeNode* node = st.top();
                st.pop();
                out.push_back(node->val);           // visit the node first
                if (node->right != NULL) st.push(node->right);   // push right first so left comes out first
                if (node->left != NULL) st.push(node->left);
            }
            return out;
        }
    };

    Python

    class Solution:
        def preorderTraversal(self, root) -> list[int]:
            out, stack = [], [root] if root else []
            while stack:
                node = stack.pop()
                out.append(node.val)                # visit the node first
                if node.right:
                    stack.append(node.right)        # push right first so left comes out first
                if node.left:
                    stack.append(node.left)
            return out

    Common mistakes

    • Pushing the left child first.
    • Pushing null children.

    Similar problems