-
-
Save GAierken/475d54f1a7d76567883935ffb722f2fc to your computer and use it in GitHub Desktop.
This file contains 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 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