root = [3,9,20,null,null,15,7]3Depth-first search explores one branch as far as possible before returning to explore another. Recursion uses the call stack; iterative DFS stores pending nodes in an explicit stack.
Imagine exploring rooms connected like a tree. Follow one branch until you cannot go farther. Then walk back to the nearest room with an unexplored branch.
The key idea
This example visits a node before its children, left side first. DFS goes deep before going sideways. Returning to a parent is not a new first visit.
Find tree depth, check root-to-leaf paths, compare subtrees, or combine child results to compute a diameter or check balance.
Find the largest number of nodes on any path from the root to a leaf. Return zero for an empty tree. Count nodes, not edges.
root = [3,9,20,null,null,15,7]3The paths 3 → 20 → 15 and 3 → 20 → 7 each contain three nodes.
root = []0An empty tree has no nodes, so its depth is zero.
The editor provides TreeNode with val, left, and right. Your function receives the root node or None, not an array.
LeetCode 104 ↗root = [3,9,20,null,null,15,7] output: 3
Every node is visited once, so time complexity is O(n).
Active calls use O(h) space, where h is the tree height. This is O(log n) for a balanced tree and O(n) for a skewed tree. Very deep trees may exceed Python's recursion limit.
root = [3,9,20,null,null,15,7] output: 3
Both approaches have O(n) time and O(h) worst-case extra space. Iteration avoids Python's recursion limit; it is not an asymptotic time optimization.
Each node is pushed and popped once, so time complexity is O(n).
Pending branches need O(h) space in the worst case, at most O(n). A single chain keeps only one pending node in this implementation.