4 ms·
wow... mine were much shorter than that. Maybe I did it wrong? var doTree = function doTree(node, fn) { for (var i = 0; i < node.children.length; i
by jiaaro 16y ago
wow... mine were much shorter than that. Maybe I did it wrong?
var doTree = function doTree(node, fn) {
for (var i = 0; i < node.children.length; i++) {
doTree(node.children[i]);
}
fn(node.value);
}
var treeSum = 0;
doTree(numTree, function(nodeValue) {
treeSum += nodeValue;
});
edit: fixed a dumb bug
edit2: nicer coding style
- justinlilly 16y agoNope. That's correct as well. Recursion is a much more elegant way of doing it. :-/
- kqr2 16y agoShould the last line be: doTree(numTree, addNodeToSum)
- jiaaro 16y agooh you're right!