Skip to content

Instantly share code, notes, and snippets.

@JayDouglass
Created August 5, 2012 07:50
Show Gist options
  • Save JayDouglass/3262697 to your computer and use it in GitHub Desktop.
Save JayDouglass/3262697 to your computer and use it in GitHub Desktop.
Nathans JS lessons 1 - count tree using recursion and iteration
/*
var count = function(tree) {
if(!tree) {
return 0;
}
return 1 + count(tree.left) + count(tree.right);
};
*/
var count = function(tree) {
var nodes = [];
var count = 0;
var currentNode;
if(tree) {
nodes.push(tree);
}
while(nodes.length) {
currentNode = nodes.shift();
count += 1;
if(currentNode.left) {
nodes.push(currentNode.left);
}
if(currentNode.right) {
nodes.push(currentNode.right);
}
}
return count;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment