Binary Tree Preorder Traversal

easy

Given the root of a binary tree, return the preorder traversal of its nodes' values — visit the node first, then the left subtree, then the right subtree.

The tree is given in level-order (breadth-first), using null for missing children.

Hints

Preorder means the node first, then the left subtree, then the right subtree.
Recursively that's three lines; iteratively use an explicit stack.
For the iterative version, push the right child before the left so the left comes off the stack first.

Common doubts

You emit each node before its children, so a rebuilder can create the node and then attach the subtrees it reads next.
A stack is last-in-first-out; pushing right first leaves the left child on top, so it's processed next — matching node-left-right order.
O(height) for the recursion/stack — O(log n) balanced, O(n) for a degenerate tree.

Interview follow-ups

A preorder walk with explicit null markers uniquely encodes a binary tree, which is the basis of many serialize/deserialize solutions.
Not from values alone unless you also record nulls or have a second traversal (e.g. preorder + inorder) to locate subtree boundaries.

Fun facts

  • Preorder traversal is exactly how you'd read a nested outline: the heading first, then its sub-points.
  • Preorder + inorder (or postorder + inorder) together uniquely determine a binary tree.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: root = [1, null, 2, 3]
Output: [1, 2, 3]
Record 1, then its left subtree (empty), then its right subtree yielding 2 then 3.
Example 2
Input: root = []
Output: []
An empty tree has no nodes.
Constraints

- The number of nodes is in the range [0, 100] - -100 <= Node.val <= 100

Solve this problem →