-
-
Save GAierken/afa6e80ae45374a5f29ef74de0073a1d 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) => { | |
//check if root is null | |
if(!root) return 0 | |
//implement queue to complete traversing | |
let queue = [] | |
//variable to increment while counting levels | |
let depth = 0 | |
//push the root to the queue | |
queue.push(root) | |
//start traverse | |
while(queue.length > 0){ | |
//n-ary with children, | |
//queue sometimes has multiple nodes of the same level | |
//we need to iterate all nodes | |
let size = queue.length | |
//set current variable to store current node | |
let current | |
//loop through the queue | |
for(let i = 0; i < size; i++){ | |
//set current as first node in the queue | |
current = queue.shift() | |
//iterate the children of the current node | |
for(let child of current.children){ | |
//push child of the same level in the queue | |
queue.push(child) | |
} | |
} | |
//after iterate same level node and move to the next level | |
//increment the depth by one | |
depth++ | |
} | |
//return the number of levels in the tree | |
return depth | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment