The natural procedure to general problem solving often follows the style set forth by the imperative paradigm: the iterative approach. Then, there is the more elegant (and somewhat more magical) recursive style. It is important to note that while recursion and iteration may be considered to be mathematically equivalent, they are not computationally equivalent.
Shown above is a depthFirstSearch function that is designed to move throughout a tree-like structure and to return an array of node values that correctly pass some arbitrary filterFunction. The exact functionality of depthFirstSearch is not particularly relevant; it is the ability to keep track of the node level that interests us. Note the pattern of incrementing and decrementing around the recursive call: this allows us to keep track of how far down we are within the tree. Indeed, as we jump in and out of the explore inner-function, we are thus able to maintain our sense of time and place.
If you are still confused and want to learn more about recursion, click here.
