Visualize Depth-First Search on a Binary Tree: pre-order, in-order, and post-order traversals, along with classic DFS patterns like Path Sum and LCA.
About this algorithm
Depth-first search on a tree goes all the way down one branch before it starts on the next. Every DFS on a binary tree makes the same moves: into the left subtree and back, then into the right subtree and back. The only choice is when to visit the node itself, and that choice gives the three orders: pre-order (before both subtrees), in-order (between them) and post-order (after both).
Use DFS when the answer at a node depends on its subtrees or on the path from the root: a subtree's height or sum, whether a root-to-leaf path adds up to a target, the lowest common ancestor of two nodes. Choose the order by when you need the node: pre-order to act on a node before its children (copying a tree, writing it out), in-order to read a binary search tree in sorted order, post-order when a node needs its children's results first (heights, sizes, deleting a tree). Pick level order (BFS) instead when the answer is about levels or the shallowest match.
Call the traversal on the root. A missing child returns at once; that base case is what stops the recursion.
Recurse into the left child and let it finish its whole subtree before anything else happens at this node.
Recurse into the right child in the same way.
Record the value before going left for pre-order, between the two calls for in-order, or after both for post-order. The recursion is identical in all three; only the line that records the value moves. This page runs in-order by default, and the pre-order and post-order pages run the other two.
The page loads root 0 with children 1 and 2, where 1 has a left child 3 and 2 has a right child 4. The walk goes from 0 down to 1, down to 3, back up to 1 and 0, then down to 2, down to 4, and back up. Recording each node at its moment gives pre-order 0, 1, 3, 2, 4, in-order 3, 1, 0, 2, 4 and post-order 3, 1, 4, 2, 0. The root comes first in pre-order, in the middle of in-order and last in post-order. The recursion is never more than 3 nodes deep, the height of this tree.
Any of the three orders can use an explicit stack instead of recursion. Pre-order is the easiest: pop a node, record it, then push its right child and its left child so the left comes off first. This avoids running out of call stack on a very deep tree, such as one built by inserting already sorted values into a binary search tree.
Time: each node is entered once and each missing child is checked once, so the work is proportional to N. Space: the call stack holds one frame per node on the current path from the root, so it grows with the height H: about log N for a balanced tree and N for a tree that is one long chain.