Skip to content

Instantly share code, notes, and snippets.

@nealfennimore
Created March 4, 2020 01:41
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 nealfennimore/11155780079b3024ff71a532fb29e9d9 to your computer and use it in GitHub Desktop.
Save nealfennimore/11155780079b3024ff71a532fb29e9d9 to your computer and use it in GitHub Desktop.
Binary Tree Depth
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