Diameter of Binary Tree

Given the root of a binary tree, return the length of its diameter: the longest path between any two nodes, measured in edges (the number of parent-child links along the path).

The path does not have to pass through the root. It may climb up from one node to some ancestor and come back down the other side to a second node, but it can't visit a node twice.

A tree with zero or one node has diameter 0.

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]
Output: 4

The longest path is 4 → 2 → 1 → 3 → 6 (or 5 → 2 → 1 → 3 → 6): 4 edges.

Example 2

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

Two nodes joined by one edge.

Example 3

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

The longest path, 7 → 5 → 3 → 2 → 4 → 6 → 8, bends at node 2 and never touches the root: 6 edges.

JavaScript you'll use: Recursion, the call stack and memoization Functions, arrow functions and closures

/**
 * 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 diameterOfBinaryTree(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.