Last active
January 5, 2020 18:42
-
-
Save cozzbie/80694d21d036ebe8f803906aa73a166c to your computer and use it in GitHub Desktop.
Get the total number of nodes in a tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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