Loading content...
Given the root of a binary tree, compute and return the length of the longest path between any two nodes within the tree.
A path in a binary tree is defined as a sequence of nodes where each adjacent pair of nodes in the sequence shares a direct parent-child edge. The path can start and end at any nodes in the tree—it does not need to include the root, nor must it pass through it.
The length of a path is measured by the total number of edges connecting the nodes along that path.
Your task is to find the maximum possible path length across all valid paths in the tree.
root = [1,2,3,4,5]3The longest path spans from node 4 to node 3 (passing through nodes 4 → 2 → 1 → 3) or equivalently from node 5 to node 3 (nodes 5 → 2 → 1 → 3). Both paths contain 3 edges, giving a length of 3.
root = [1,2]1The tree has only two nodes (1 and 2) connected by a single edge. The longest path is between these two nodes, containing exactly 1 edge.
root = [1,2,3]2The tree has three nodes: root 1 with left child 2 and right child 3. The longest path goes from node 2 through root 1 to node 3, containing 2 edges.
Constraints