So help me out here. I was given the following code problem:

1 2 3 4 |
var Tree = function(value) { this.value = value; this.children = []; }; |

1 2 3 4 |
Tree.prototype.addChild = function(child){ // code removed to protect the innocent! // returns a new child node/leaf }; |

and asked to implement a ‘countLeaves’ function that traverses the tree and counts all the leaves. Some examples of trees are below:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
* (tree with five leaves) / \ * * / \ / \ * * * * / / \ * * * * (tree with three leaves) / \ * * / \ * * / * |

I wrote the code rather quickly and surprised myself by writing the following. It’s the first time I’ve felt like I actually *got* recursive functions!

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Tree.prototype.countLeaves = function () { var count = 0; //set counter equal to zero var recurseCount = function(tree) { //walk the tree if (tree.children.length === 0) { //if no children count++; //increase count and return **BASE CASE** return; } for (var i = 0; i < tree.children.length; i++) { //loop through children recurseCount(tree.children[i]); //call recursive function with child tree } }; recurseCount(this); //call recursive function with "this" return count; //return number of leaves } |

So is the answer really this easy? Let me know what you think!