I needed to do an n-ary tree traversal recently with some Javascript code that I'm working on and I initially wrote an iterative n-ary tree-traversal algorithm (using a node stack with a while loop). I wanted to keep track of some extra (depth-dependent) data during the traversal and I didn't like the way I was forced to do it with the iterative algorithm. I also didn't feel like adding a new function to the namespace. Then I realized that you can create function-literals in Javascript and self-invoke them. So I ended up with the an anonymous self-invoked recursive function. Here's the basic skeleton for an n-ary tree traversal (this one is pre-order):
<pre class="wp-block-syntaxhighlighter-code">(function(node) {
for(var i = 0; i < node.children.length; i++) {
console.log(node.data);
arguments.callee(node.children[i]);
}
}(root));</pre>
You can also do a binary tree traversal (this one is also pre-order):
(function(node) {
if(node != null) {
console.log(node.data);
arguments.callee(node.left);
arguments.callee(node.right);
}
}(root));
Seems very elegant and also very Lisp-like to me (must be the parentheses!)