Find the Longest Link Between Any Two Nodes

Implement longestLink

You are given the root of a binary tree. Return the length of the longest path between any two nodes in the tree, counted in connections (edges) rather than nodes. The path may pass through the root, but it does not have to.

The longest path that bends at a given node uses the taller branch on each side of it. Working out the heights once, from the bottom up, and updating a running best at every node avoids recomputing them.

Example 1:

Input: root = [9,5,null,3,7,2,null,6,8]

Output: 4

Example 2:

Input: root = [4,null,6,null,9]

Output: 2

Example 3:

Input: root = [5]

Output: 0

+ 11 hidden test cases run on Submit.

Constraints:

  • ●0 ≤ number of nodes ≤ 100
  • ●−100 ≤ node.val ≤ 100 (the values never affect the answer)
  • ●The tree is given as its root node (null for an empty tree); each node has a val, a left child and a right child
  • ●A link between two nodes is the unique path that joins them through parent-child connections; its length is the number of connections (edges) on it. The path may pass through any node, not necessarily the root. Return the length of the longest such path (0 for an empty or single-node tree)

root =

[9, 5, null, 3, 7, 2, null, 6, 8]