Dive into Depth-First Search (DFS) on binary trees! In this friendly guide, we’ll learn about preorder, inorder, and postorder traversals using simple Python recursion, perfect for LeetCode prep and coding interviews.
Why Tree Traversals Matter
Imagine you’re exploring a hidden maze. At each junction, you choose a path, dive deep until you hit a dead end, then backtrack. That’s essentially Depth-First Search (DFS) in action. When our “maze” is a binary tree, DFS gives us three classic ways to visit every node:
- Preorder: Visit the root before its subtrees.
- Inorder: Visit the root between its left and right subtrees.
- Postorder: Visit the root after its subtrees.
These traversal patterns aren’t just academic, they’re the backbone of many LeetCode challenges (think “Validate BST” or “Serialize/Deserialize Tree”) and are super common in whiteboard interviews.
Let’s check each one, build up the intuition, and then translate it into clean, recursive Python code.
Also read about the Python Program to Level Order Traversals in Binary Trees.
Quick Visual: The Binary Tree We’ll Use
1
/ \
2 3
/ \ \
4 5 6
- Preorder: visit 1, then traverse left, then right →
[1, 2, 4, 5, 3, 6]
- Inorder: traverse left, visit 1, then right →
[4, 2, 5, 1, 3, 6]
- Postorder: traverse left, then right, visit 1 →
[4, 5, 2, 6, 3, 1]
Keep these sequences in mind as we code!
1. Preorder Traversal (Root → Left → Right)
Intuition & “Why”
- You’re a scout: you capture the root first (mark it visited), then explore deeper on the left branch, then on the right.
- Great for copying a tree (clone its structure).
Recursive Code (Python)
def preorder(root, result):
if not root:
return
# Visit the root
result.append(root.val)
# Explore left
preorder(root.left, result)
# Explore right
preorder(root.right, result)
res = []
preorder(root, res)
print(res) # [1, 2, 4, 5, 3, 6]
2. Inorder Traversal (Left → Root → Right)
Intuition & “Why”
- You’re reading a book: you finish the left chapter, then read the root, then tackle the right chapter.
- In a binary search tree (BST), inorder traversal gives you sorted order, super useful for checking if a tree is a valid BST.
Recursive Code (Python)
def inorder(root, result):
if not root:
return
# Explore left
inorder(root.left, result)
# Visit the root
result.append(root.val)
# Explore right
inorder(root.right, result)
res = []
inorder(root, res)
print(res) # [4, 2, 5, 1, 3, 6]
3. Postorder Traversal (Left → Right → Root)
Intuition & “Why”
- You’re cleaning the mansion: clean left wing, clean right wing, and finally lock up the main door (root).
- Perfect for deleting or freeing nodes: you want to handle children before the parent.
Recursive Code (Python)
def postorder(root, result):
if not root:
return
# Explore left
postorder(root.left, result)
# Explore right
postorder(root.right, result)
# Visit the root
result.append(root.val)
res = []
postorder(root, res)
print(res) # [4, 5, 2, 6, 3, 1]
Putting It All Together
Here’s a single class encapsulating all three traversals neatly:
class DFSBinaryTree:
def preorder(self, root, res):
if not root: return
res.append(root.val)
self.preorder(root.left, res)
self.preorder(root.right, res)
def inorder(self, root, res):
if not root: return
self.inorder(root.left, res)
res.append(root.val)
self.inorder(root.right, res)
def postorder(self, root, res):
if not root: return
self.postorder(root.left, res)
self.postorder(root.right, res)
res.append(root.val)
Example:
traversals = DFSBinaryTree()
pre, ino, post = [], [], []
traversals.preorder(root, pre)
traversals.inorder(root, ino)
traversals.postorder(root, post)
print("Preorder =", pre) # [1, 2, 4, 5, 3, 6]
print("Inorder =", ino) # [4, 2, 5, 1, 3, 6]
print("Postorder =", post) # [4, 5, 2, 6, 3, 1]
Why Recursion Rocks for DFS
- Elegance: The call stack naturally tracks which node you came from, no need for manual stacks or markers.
- Clarity: Each function call focuses on one node, delegating subtrees to deeper calls.
- Conciseness: A few lines of code handle the entire traversal.
For any changes to the document, kindly email at code@codeanddebug.in or contact us at +91-9712928220.