Given the root of a binary tree, return the length of the longest path between any two nodes in it.
The length of a path is the number of edges on it, so a single node has length 0. The path is not required to pass through the root.
Tree Encoding
Your function receives root as a TreeNode. The tree always has at least one node, and the node type is provided for you, with val, left, and right fields.
The examples below write the tree as its level-order traversal, where null marks a missing child of a listed node and trailing nulls are omitted. That is only how the input is displayed; the decoding is done for you.
Constraints
The number of nodes in the tree is in the range [1,104].
−100≤Node.val≤100
Examples
Example 1
Input
root = [1, 2, 3, 4, 5]
root
Output
3
Explanation
The longest path runs 4 - 2 - 1 - 3 (or 5 - 2 - 1 - 3), which is 3 edges. It bends at node 1 rather than descending from it.
Example 2
Input
root = [1, 2]
root
Output
1
Explanation
The only path between two nodes is the single edge from 1 to 2.
Loading editor...
Log in to run your code. Your draft is saved in this browser.Log inSign up