Magicsheet logo

Binary Tree Preorder Traversal

Easy
34%
Updated 6/1/2025

Binary Tree Preorder Traversal

What is this problem about?

Binary Tree Preorder Traversal is a fundamental tree traversal algorithm where nodes are visited in the order: Root, Left Subtree, and then Right Subtree. This traversal is particularly useful when you need to create a copy of a tree or when you need to process a node before its children (e.g., evaluating a prefix expression). The problem asks you to return the values of the nodes in this specific sequence.

Why is this asked in interviews?

This is a standard interview question at companies like Meta, Amazon, and Microsoft to verify a candidate's baseline understanding of data structures. While the recursive implementation is straightforward, interviewers often use it as a stepping stone to discuss iterative solutions using stacks. It tests your ability to visualize how information flows through a tree and how to manage a LIFO (Last-In-First-Out) structure to mimic recursion.

Algorithmic pattern used

The two main patterns are Recursion and the Stack interview pattern. In the iterative approach, you use a stack to keep track of nodes to visit. You push the root to the stack, and while the stack isn't empty, you pop a node, record its value, and then push its right child followed by its left child (so that the left child is processed first).

Example explanation

Consider this tree: 1 / 2 3 / 4 5

Preorder: Root -> Left -> Right

  1. Process root: [1].
  2. Go left to 2. Process: [1, 2].
  3. Go left to 4. Process: [1, 2, 4].
  4. Backtrack to 2, then go right to 5. Process: [1, 2, 4, 5].
  5. Backtrack to 1, then go right to 3. Process: [1, 2, 4, 5, 3]. Final sequence: [1, 2, 4, 5, 3].

Common mistakes candidates make

The most frequent mistake in the iterative version is pushing children to the stack in the wrong order. To process the left child first, you must push the right child to the stack before the left child. Other mistakes include not handling the null root case or forgetting to check if a child exists before pushing it to the stack.

Interview preparation tip

Practice implementing preorder, inorder, and postorder traversal both recursively and iteratively. Being able to code these fluently is a minimum requirement for any technical interview involving trees. For preorder specifically, remember that the root is always the first element in the output.

Similar Questions