Coding Tactic: Why would you use recursion?
This is the best explanation I’ve seen on the topic:
Traversing a tree is the best example. How a tree is composed of nodes. Each node has data and children, which themselves are nodes. So you can break the problem down into:
- Do something to the node
- Do something to each child
But since each child is itself a node. You can simplify it to:
- Do something to each node
- Repeat for every child
This way you don’t have to worry about how complex the tree is, you just need to write a function that can operate on a single node, and then call itself for every child. And then it can handle a tree of any size or shape.