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:
Depth-First Search (DFS)
- Inorder Traversal
- Preorder Traversal
- Postorder Traversal
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 current = current.left
8 current = …Keep your momentum going
Create a free account to unlock the full lesson, all 60 days, and track your progress as you go.
- Full access to all 60 daily lessons
- Track completion and build a daily streak
- Get interview-ready, one algorithm at a time
Join 2,900+ learners · 4.8/5 average rating