Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Created March 24, 2017 21:40
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save primaryobjects/638a4fbc295537a4a72b88f213495d97 to your computer and use it in GitHub Desktop.
Finding the maximum depth of a binary tree in JavaScript.
/**
* 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;
};
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