Back to: Python Data Structure and Algorithims
Coding Depth First Search (DFS) — Inorder Traversal Explained
In the previous post, we explored what Inorder Traversal means conceptually —
a method of visiting a binary tree’s nodes in the order: Left → Visit → Right.
Now, it’s time to bring that theory to life through code!
Let’s walk step-by-step through how the algorithm works internally — using our call stack and our binary tree.
🌿 Our Example Binary Tree
Here’s the same tree we’ve been using throughout this series:
We’ll perform Inorder DFS traversal on this tree.
That means:
-
Go left as far as possible,
-
Write the value of the current node,
-
Then go right.
🧠Step 1: Writing the Method
We’ll start by defining a method named dfs_inorder().
It will create an empty list called results to hold our output.
Just like in Preorder and Postorder traversals,
we’ll define a nested helper function called traverse(node) that handles recursion.
The only difference between the three DFS types is the order of operations:
| Traversal Type | Order |
|---|---|
| Preorder | Visit → Left → Right |
| Postorder | Left → Right → Visit |
| Inorder | Left → Visit → Right |
So, for Inorder, we’ll go left, then write, then right.
💻 Step 2: Python Code
Here’s the implementation: