"Maxium depth of binary tree" Leetcode problem
Published on: 2020.06.22One of the problems you might stumble upon in Leetcode is the "Maxium depth of binary tree".
You're given a tree's root node. Your job is to count how many levels deep is the given tree. If you click the link to the problem, there's a simple exmaple:
As you can clearly see from the example the author provided, the depth
of the tree is 3
How to approach such a problem?
The most obvious approach regarding problems that involve tree-traversal, is to use recursion. Such is the case here. Of course, in most of the cases recursion can be avoided at the expense of not-so-elegant iterative solution with `for/while` loops. In my solution I'm sticking to the recursion.
Solution
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
function traverseTree(node, depth) {
if (node === null) {
return depth;
}
const leftDepth = traverseTree(node.left, depth + 1);
const rightDepth = traverseTree(node.right, depth + 1);
return Math.max(leftDepth, rightDepth);
}
return traverseTree(root, 0);
};
Exmplanation
As you see, I have declared an inner function, which is going to call itself until there is a valid node (node !== null
)
In the body of the recursive function I roll the traversal of the left side of the tree and the right side of the tree, incrementing the depth of the respective side by one each time. Once the recursion ends, I simply return the Math.max
of left and right side.