progress

~/problems / Trees / Binary trees

Preorder, inorder and postorder

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

TreeNode(val, left=None, right=None) is in the starter. Keep it.

Every tree recursion is one of three orders, depending on when you handle the node relative to its subtrees. Write all three, each returning the list of values visited:

  • preorder(root): node, then left subtree, then right subtree.
  • inorder(root): left, node, right. (For a binary search tree this is sorted order.)
  • postorder(root): left, right, node.

An empty tree (None) gives [].

#        1
#       / \
#      2   3
#     / \
#    4   5
preorder(root)    # [1, 2, 4, 5, 3]
inorder(root)     # [4, 2, 5, 1, 3]
postorder(root)   # [4, 5, 2, 3, 1]

Up to 500 nodes, so plain recursion is fine. Values may repeat or be negative.

Show hint

all three share one recursive skeleton; only the line that records node.val moves.

Topic: Binary trees. Recursive return values (height, best path), BFS by level, BST invariants.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc