Loading...
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.
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.
Node.val ≤100The 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.
The only path between two nodes is the single edge from 1 to 2.
Click "Run" to test with sample cases or "Submit" to run all tests.