Stage 1 · Code
Trees
DFS
Preorder, inorder, postorder traversals recursively and iteratively.
6 min readMastering Data Structures & Algorithms for Software Engineering InterviewsCode
Recursive DFS
DFS pre-order traversal — watch the stack as nodes are visited
DFS Tree Traversal (pre-order)
Stack:1
Step 1 / 12 — Start: push root onto stack
Gothree-recursive-traversals.go
42 linesLn 1, Col 1Go
Closure captures result slice. Order of append determines traversal type. Simple and readable but uses O(h) call stack.
Iterative DFS
Use explicit stack. Preorder: push right then left (so left pops first). Inorder: traverse left while pushing, then process, go right. Postorder: modified preorder (root-right-left) then reverse.
Goiterative-traversals.go
56 linesLn 1, Col 1Go
Preorder: stack with right then left. Inorder: go left pushing, then process, go right. Postorder: root-right-left then reverse.
DFS Applications
- Path sum: Root-to-leaf paths summing to target.
- Max depth: Height of tree.
- Diameter: Longest path between any two nodes.
- Serialize/deserialize: Preorder with null markers.
- LCA: Lowest common ancestor using recursion.
- Tree symmetry: Mirror check with two pointers.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.