Last active
September 15, 2021 05:29
-
-
Save o-az/f758795bbdc2d50271cbc19b9565f673 to your computer and use it in GitHub Desktop.
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
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