AlgoInsight

DSA problem

Binary Tree Preorder Traversal

EasyTree Traversal - Pre OrderPattern: Tree Traversal - Pre Ordertop75FreeAmazonMicrosoftGoogleAppleMetaBloomberg

Given the root of a binary tree, return the preorder traversal of its nodes' values. Preorder visits each node in the order root → left subtree → right subtree, so the very first value emitted is always the root, followed recursively by the entire left subtree, then the entire right subtree.

Preorder is the natural traversal whenever you want to process a node before descending into its children. It mirrors how you would copy a tree (you must clone the node first so the children have somewhere to attach), how you would serialize a tree to a string, and how prefix-expression evaluators read operators before their operands. Understanding the iterative form of this traversal is foundational for many tougher tree problems.

The recursive solution is a textbook three-liner: visit the current node, recurse left, then recurse right. It is clean and obvious, but it consumes O(h) call-stack frames where h is the tree's height, which can be O(n) in the worst case for a skewed tree.

The iterative solution swaps the implicit call stack for an explicit one. Push the root onto the stack, then in a loop pop a node, record its value, and push its right child first followed by its left child — pushing right first ensures left is popped (and therefore visited) first, preserving the root-left-right order. Both forms run in O(n) time; the iterative form makes the data flow visible and is the canonical implementation you should be ready to write under interview pressure.

Examples

Example 1
Input: root = [1,null,2,3]
Output: [1,2,3]
Explanation: Visit root 1 first; the left subtree is empty so we descend to the right child 2; from node 2 we descend into its left child 3. The emission order is 1, 2, 3.
Example 2
Input: root = []
Output: []
Explanation: An empty tree has no nodes to visit, so the traversal returns an empty list.
Example 3
Input: root = [1,2,3,4,5,null,6]
Output: [1,2,4,5,3,6]
Explanation: Root 1, then left subtree rooted at 2 (which visits 2, 4, 5 in preorder), then right subtree rooted at 3 (which visits 3, 6).

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

treebinary-treestackdepth-first-search

Browse all DSA problems