Web Analytics

๐Ÿ”„ Tree Traversals

Intermediate ~25 min read

Imagine you're reading a book. You could read it page by page (linear), or you could read the table of contents first, then each chapter's introduction, then the details (hierarchical). Similarly, there are different ways to visit all nodes in a tree - each useful for different purposes!

Why Different Traversals?

Just like there are different ways to explore a building (top-down, bottom-up, floor-by-floor), trees can be traversed in different orders depending on what you need to do:

Real-World Analogies

  • File System: List files in sorted order (inorder)
  • Backup: Copy folder structure first (preorder)
  • Delete: Delete files before folders (postorder)
  • Search: Check closest folders first (level-order)

The Four Main Traversals

There are two categories: Depth-First (go deep) and Breadth-First (go wide).

See Them in Action

1. Inorder: Left โ†’ Root โ†’ Right

How It Works

  1. Visit left subtree
  2. Visit root
  3. Visit right subtree

Key property: For Binary Search Trees, gives values in sorted order!

When to Use Inorder

  • Get sorted values from BST
  • Validate if tree is a BST
  • Find kth smallest element

2. Preorder: Root โ†’ Left โ†’ Right

How It Works

  1. Visit root
  2. Visit left subtree
  3. Visit right subtree

Key property: Visits parent before children - perfect for copying!

When to Use Preorder

  • Copy/clone a tree
  • Serialize tree to string
  • Create prefix expressions

3. Postorder: Left โ†’ Right โ†’ Root

How It Works

  1. Visit left subtree
  2. Visit right subtree
  3. Visit root

Key property: Visits children before parent - perfect for deletion!

When to Use Postorder

  • Delete tree (delete children first)
  • Evaluate postfix expressions
  • Calculate tree height/size

4. Level-order: Level by Level (BFS)

How It Works

  1. Visit all nodes at level 0 (root)
  2. Visit all nodes at level 1
  3. Visit all nodes at level 2
  4. Continue until all levels visited

Key difference: Uses a queue instead of recursion!

When to Use Level-order

  • Find shortest path in tree
  • Print tree level by level
  • Serialize tree for transmission

Recursive vs Iterative

All DFS traversals can be implemented two ways:

Comparison

Aspect Recursive Iterative
Code Cleaner, shorter More verbose
Stack Uses call stack Uses explicit stack
Space O(h) O(h)
Control Less control More control

The Complete Code

Output
Click Run to execute your code

Summary

What You've Learned

Tree traversals are systematic ways to visit all nodes:

  1. Inorder (L-Root-R): Sorted order for BST
  2. Preorder (Root-L-R): Copy tree structure
  3. Postorder (L-R-Root): Delete tree safely
  4. Level-order (BFS): Level by level with queue
  5. All are O(n) time: Visit each node once

What's Next?

Now that you can traverse any tree, let's learn about Binary Search Trees (BST) - a special tree where inorder traversal gives sorted values, enabling O(log n) search!