Log In Sign Up
Day 16

Day 16: Tree Traversals

16/60 Days

Tree Traversals #

Welcome to Day 16 of our 60 Days of Coding Algorithm Challenge! Today, we’ll dive deep into various tree traversal techniques, exploring both recursive and iterative approaches. Tree traversals are fundamental operations for processing tree-based data structures and are crucial for solving many algorithmic problems.

Types of Tree Traversals #

There are two main categories of tree traversals:

  1. Depth-First Search (DFS)

    • Inorder Traversal
    • Preorder Traversal
    • Postorder Traversal
  2. Breadth-First Search (BFS)

    • Level Order Traversal

Let’s explore each of these in detail.

Depth-First Search (DFS) Traversals #

1. Inorder Traversal (Left, Root, Right) #

Inorder traversal visits the left subtree, then the root, and finally the right subtree.

Recursive Approach: #

1def inorder_recursive(root):
2    if root:
3        inorder_recursive(root.left)
4        print(root.val, end=" ")
5        inorder_recursive(root.right)

Iterative Approach: #

 1def inorder_iterative(root):
 2    stack = []
 3    current = root
 4    while stack or current:
 5        while current:
 6            stack.append(current)
 7 …