Maximum Depth of a Binary Tree in Javascript
Another common coding interview question I’ve seen is finding the maximum depth of a binary tree. Here’s a solution that I’ve created to solving the problem on LeetCode. I’ll also break down the solution line-by-line here so that you too will be able to solve it.
/**
* 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) {
// use a handler function since it's easier to write and think about recursive code this way. You start at a num/depth value of 1 because of the definition of depth.
return maxDepthHandler(root,1)
};var maxDepthHandler = function(root, num){// here's just base case -- if you get an empty root(because you definitely will at some point, just return a depth of zero because there's nothing in the tree!if(root == null){
return 0
}// this is your terminating case. a leaf node doesn't have any children, and so the root at that point will have null value. at this point just return the depth/num if (root.right == null && root.left == null){
return num
}//Use Math.max to get the highest between the two root depths. the rest of this code is just handling the individual root cases. if (root.right && root.left){
return Math.max( maxDepthHandler(root.right, num+1), maxDepthHandler(root.left, num + 1))
} else if (root.right != null){
return maxDepthHandler(root.right, num+1)
} else {
return maxDepthHandler(root.left, num+1)
}
};
So I think the code’s pretty well commented here but let’s break down the approach to the problem. You know it’s a tree problem, so when in doubt, you can probably use recursion to solve it. I set up a handler function maxDepthHandler(root, num) in order to both hold onto the current depth of the tree as well as design my recursive algorithm more gracefully.
Within my maxDepthHandler function, I account for the cases that I see — a null case (when the root is just null), a base/terminating case( for when the tree has come to a leaf node), and a recursive case (when you’re in the middle of a tree, keep searching by calling maxDepthHandler on the next child node(s).
Good luck to everyone interviewing out there! I hope this helps.