This question can be solved via recursion depth first search. Keep track of the max depth. Traverse left sub tree then traverse right sub tree - increase the depth each level.
Link: Maximum Depth of Binary Tree
/**
* 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) {
let max = 0;
let dfs = (node, lvl) => {
if(!node) return;
if(lvl>max){
max = lvl;
}
if(node.left){
dfs(node.left, lvl+1);
}
if(node.right){
dfs(node.right, lvl+1);
}
};
dfs(root, 1);
return max;
};