Created
March 4, 2020 01:41
-
-
Save nealfennimore/11155780079b3024ff71a532fb29e9d9 to your computer and use it in GitHub Desktop.
Binary Tree Depth
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
const getBTreeDepth = (tree) => { | |
const isEmpty = arr => arr.every(item => item === -1) | |
let nodes = 1; | |
let depth = 0; | |
let start = 0; | |
let end = 1; | |
while (nodes <= tree.length) { | |
const clone = tree.slice(start, end); | |
if (! clone.length || isEmpty(clone)) { | |
break; | |
} | |
depth++; | |
nodes *= 2; | |
start = end; | |
end = end + nodes; | |
} | |
return depth; | |
}; | |
console.assert( getBTreeDepth([0]) === 1 ) | |
console.assert( getBTreeDepth([0, 2, 3 ]) === 2 ) | |
console.assert( getBTreeDepth([0, 1, 2, -1, -1, -1, -1]) === 2 ) | |
console.assert( getBTreeDepth([0, 1, 2, 1, -1, -1, -1, 1,2,3,4,5,6,7,8,1]) === 5 ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment