Choose recursion for structure, iteration for explicit control
Recursive tree traversal closely matches a tree's definition. An iterative version stores the same unfinished work in an explicit stack, which can be easier to limit, inspect, and resume.
fun factorial(n: Int): Long {
require(n in 0..20)
var result = 1L
for (value in 2..n) result *= value
return result
}
The range includes only valid multiplication factors, and the bound prevents Long factorial overflow. The result for zero is one because the loop executes zero times. A straightforward recursive factorial has the same linear number of multiplications but adds linear stack usage.
An explicit stack does not make a traversal constant-space if it still stores O(n) pending nodes. Compare actual live state, not just whether a function calls itself.
Exercise
Implement both factorial versions and compare all inputs from zero through twenty. For a skewed tree, sketch the maximum live stack depth of recursive DFS and explicit-stack DFS.
Check: choose based on depth guarantees, readability, and runtime constraints rather than treating either style as universally faster.