Maximum Depth of Binary Tree

You are given the root of a binary tree. Return its maximum depth: the number of nodes on the longest path that starts at the root and goes down to a leaf (a node with no children).

An empty tree (root is null) has depth 0, and a tree with a single node has depth 1.

Trees in the examples are written in level order: the values row by row, left to right, with null where a child is missing. Your function receives the root TreeNode (with val, left and right), not the array.

Constraints

  • The tree has between 0 and 10^4 nodes.
  • -100 <= Node.val <= 100

Examples

Example 1

Input: root = [1,2,3,4,5,null,6,null,null,7]
Output: 4

The longest root-to-leaf path is 1 → 2 → 5 → 7, which has 4 nodes.

Example 2

Input: root = [1,null,2]
Output: 2

The root has only a right child: 1 → 2 is 2 nodes.

Example 3

Input: root = []
Output: 0

An empty tree has no nodes, so its depth is 0.

JavaScript you'll use: Recursion, the call stack and memoization Linked list and tree nodes

/**
 * Tree nodes are provided (you don't need to define them):
 * class TreeNode { constructor(val = 0, left = null, right = null) { this.val = val; this.left = left; this.right = right; } }
 */
/**
 * @param {TreeNode | null} root
 * @return {number}
 */
function maxDepth(root) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.