Binary Tree Preorder Traversal

Easy

Topics
TreeDFSStack

Given the root of a binary tree, return its preorder traversal (node, left, right) as a list of values.

Example 1

113322
visited first
The small number above each node is its position in the output: node, left subtree, right subtree, giving [1, 2, 3]. The node is emitted before either subtree, which is why this order can rebuild the tree from scratch. The iterative version swaps the call stack for an explicit one.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [1,null,2,3]
Output: [1,2,3]

Example 2

4322541135
visited first
Input:  root = [1,2,3,4,5]
Output: [1,2,4,5,3]

Constraints

  • 0 <= number of nodes <= 100
  • -100 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

Preorder visits the node before its subtrees: node, then left, then right.

Approach

  1. Append the current node’s value.
  2. Recurse left, then recurse right.

Dry Run

        1
      /   \
     2     3
    / \
   4   5
Preorder appends before descending anywhere:
  at 1: VISIT                res 1
        descend left
    at 2: VISIT              res 1 2
          descend left
      at 4: VISIT            res 1 2 4
            both children null
          descend right
      at 5: VISIT            res 1 2 4 5
            both children null
        descend right
    at 3: VISIT              res 1 2 4 5 3
          both children null
answer 1 2 4 5 3
The root arrives first and each node arrives before anything beneath it. That is
why preorder is the traversal you serialise with: a reader rebuilding the tree
always has the parent in hand before its children show up, so it can attach them
without buffering.
The descent is the same for all three traversals; only where res.append sits
changes the output:
  preorder    1 2 4 5 3      append before descending
  inorder     4 2 5 1 3      append between the two descents
  postorder   4 5 2 3 1      append after both descents
Note the left subtree is finished entirely before the right begins -- 2, 4 and 5
all land before 3, even though 3 is shallower than 4 and 5. Preorder is depth
first, not level by level.

Complexity

  • Time — O(n): each node visited once.
  • Space — O(h): stack up to height h.

Common Pitfalls

  • The visit comes first, before either recursive call. Moving it after both gives postorder: 4 5 2 3 1 where preorder is 1 2 4 5 3.
  • Preorder is the one that serialises a tree you can rebuild, because the root arrives before anything that depends on knowing it.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def preorderTraversal(self, root):
        res = []
        def dfs(node):
            if not node:
                return
            res.append(node.val)
            dfs(node.left)
            dfs(node.right)
        dfs(root)
        return res
SensAI
Beta
Tap the mic to stop voice mode