Skip to content

Instantly share code, notes, and snippets.

@o-az
Last active September 15, 2021 05:29
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 o-az/f758795bbdc2d50271cbc19b9565f673 to your computer and use it in GitHub Desktop.
Save o-az/f758795bbdc2d50271cbc19b9565f673 to your computer and use it in GitHub Desktop.
function treeHeight(tree) {
if (tree === null) return 0;
let subHeights = Array.from(tree.children).map(treeHeight)
return Math.max(...subHeights, 0) + 1
}
// Another option is to traverse DOM layer by layer
function treeHeight2(tree) {
if (tree === null) return 0;
const queue = [tree]
let height = 0
while (queue.length) {
let count = queue.length
height += 1
while (count) {
const head = queue.shift()
queue.push(...head.children)
count -= 1
}
}
return height
}
// Example
const node = document.getElementById("main");
console.log(treeHeight(mainNode));
console.log(treeHeight2(mainNode));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment