Skip to content

Instantly share code, notes, and snippets.

@GAierken
Created October 9, 2020 01:48
Show Gist options
  • Save GAierken/475d54f1a7d76567883935ffb722f2fc to your computer and use it in GitHub Desktop.
Save GAierken/475d54f1a7d76567883935ffb722f2fc to your computer and use it in GitHub Desktop.
const maxDepth = (root) => {
//if root is undefined, depth is 0
if(!root) return 0
// variable to store the maximum levels
let max = 0
//helper function to traverse the tree
//recursively increment the levels by one
const dfs = (node, levels) => {
//compare levels and max to pass the maximum levels
if(levels > max) max = levels
//traverse all children of the current node
for(let child of node.children){
//increment the levels by one
dfs(child, levels + 1);
}
}
//when root is not null, the tree has at least one level,
//so we pass down 1
dfs(root, 1)
//return the maximum levels
return max
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment