Skip to content

Instantly share code, notes, and snippets.

@cozzbie
Last active January 5, 2020 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cozzbie/80694d21d036ebe8f803906aa73a166c to your computer and use it in GitHub Desktop.
Save cozzbie/80694d21d036ebe8f803906aa73a166c to your computer and use it in GitHub Desktop.
Get the total number of nodes in a tree
// Iterative
const size = (tree) => {
const axe = [tree];
let total = 0;
if(!tree){
return n;
}
while(axe.length) {
const n = axe.shift();
total++;
n.left && axe.push(n.left);
n.right && axe.push(n.right);
}
return total;
}
// Recursive
const size = (tree) => {
if(!tree){
return 0;
}
return size(tree.left) + 1 + size(tree.right);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment