DSA in DartMedium30 XP3 min read
How do you use recursion and when should you avoid it in Dart?
TL;DR: Recursion is clean for tree/graph traversal and divide-and-conquer algorithms. Avoid deep recursion in Dart — it lacks tail-call optimization. For deep stacks (>10K), use an iterative approach with an explicit stack.
Full Answer
Dart compiles to native or JS — neither guarantees tail-call optimization. A recursive function with depth > ~10,000 will cause a stack overflow.
Safe Use Cases
- ▸Widget tree traversal (bounded depth, usually <100)
- ▸Quicksort / merge sort (log n depth)
- ▸JSON tree parsing (depth < 50 in practice)
- ▸Binary tree operations
⚠️
File system traversal or graph traversal with arbitrary depth should use an iterative approach with a Queue or explicit Stack to avoid stack overflow.
Code Examples
dartRecursive tree traversal vs iterative
Output
// Both produce same result // Iterative: handles 1M+ nodes without stack overflow
Common Mistakes
- ✗Using recursion on deeply nested JSON from APIs — can stack overflow with complex responses
- ✗Not defining the base case first — infinite recursion crashes the app
Interview Tip
💡
Dart lacks TCO (tail call optimization). For Flutter specifically, widget tree traversal is safe recursively (bounded depth). For production algorithms, know when to switch to iterative.
#recursion#stack-overflow#tail-recursion#tree-traversal