Trees and binary search trees · Exercise 29 of 100

Preorder traversal

Visit a node as soon as you reach it, then traverse its left subtree and its right subtree in that order. This puts every parent before its children, which is useful when a child needs information from its parent.

Try it yourself

Root 12 has children 5 on the left and 20 on the right. Node 5 has only a right child, 9. Node 20 has only a left child, 16. What value do you visit immediately after 9 in preorder?

One-step hint

After visiting the leaf 9, retrace your path until you find an unexplored branch. Preorder visits the root of that branch first.

Worked solution
  1. Visit 12 first, then 5. Following the right link from 5 takes you to 9 and finishes the left subtree of 12.
  2. Return to 12 and enter its right subtree. Visit that subtree's root, 20, before descending to 16.
DSA compiler