Skip to content
Problem 144 · LeetCode 144(opens in a new tab)

Binary Tree Preorder Traversal

EasyDepth-first search

A binary tree is given by its root. List the values of its nodes in preorder: first the node itself, then everything in its left subtree, then everything in its right subtree, applying the same rule inside each subtree.

An empty tree gives an empty list.

Example 1

Input:  root = [4, 2, 7, 1, 3, null, 9]
Output: [4, 2, 1, 3, 7, 9]
Why:    4, then its left side 2, 1, 3, then its right side 7, 9
2 more examples and the constraints

Example 2

Input:  root = [5, null, 8, 6]
Output: [5, 8, 6]
Why:    5 has only a right child 8, whose left child is 6

Example 3

Input:  root = []
Output: []
Why:    there are no nodes to visit

Constraints

  • 0 ≤ number of nodes ≤ 100
  • −100 ≤ Node.val ≤ 100
  • Follow-up: do it without recursion

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. RecursionO(n)
  2. Loop with a stackO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100 nodesVerdict
RecursionO(n)
Shortest code; uses the call stack
Loop with a stackO(n)
Best; answers the follow-up

n = number of nodes, h = height of the tree. Both visit each node once.

Edge cases to test

  • Empty tree. root is null: return [] without pushing anything.
  • One node. [11] gives [11].
  • A one-sided chain. [3, 2, null, 1] gives [3, 2, 1]; the stack never holds more than one node.
  • Repeated values. Values can repeat, so track nodes, not values.

Common mistakes

  • Pushing the left child before the right, which pops the right subtree first.
  • Pushing null children and then reading .val on them.
  • Forgetting the empty tree and pushing a null root.

How to talk through it

  1. 1Clarify. Can the tree be empty? Do you want the values or the nodes?
  2. 2Define the order. Node, then left subtree, then right subtree.
  3. 3Give the recursion. Three lines; O(n) time and O(h) stack.
  4. 4Turn it into a loop. Use an explicit stack; push right before left and say why.
  5. 5Test out loud. Run the empty tree, one node and a one-sided chain.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?