-
-
Save myquery/5fd479f317165dfa263e3985164e7fb2 to your computer and use it in GitHub Desktop.
Finding the maximum depth of a binary tree in JavaScript.
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
/** | |
* Definition for a binary tree node. | |
* function TreeNode(val) { | |
* this.val = val; | |
* this.left = this.right = null; | |
* } | |
*/ | |
/** | |
* @param {TreeNode} root | |
* @return {number} | |
*/ | |
var maxDepth = function(root) { | |
var fringe = [{ node: root, depth: 1 }]; | |
var current = fringe.pop(); | |
var max = 0; | |
while (current && current.node) { | |
var node = current.node; | |
// Find all children of this node. | |
if (node.left) { | |
fringe.push({ node: node.left, depth: current.depth + 1 }); | |
} | |
if (node.right) { | |
fringe.push({ node: node.right, depth: current.depth + 1 }); | |
} | |
if (current.depth > max) { | |
max = current.depth; | |
} | |
current = fringe.pop(); | |
} | |
return max; | |
}; |
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
Given a binary tree, find its maximum depth. | |
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment