Loading...
You are given the root of a binary tree, root. Return the length of the longest path whose values are consecutive integers.
A path is a sequence of distinct nodes where each consecutive pair is directly connected as parent and child. A path can go up through a node and back down through one of its children, turning at most once, at its highest node.
Reading a path's values from one end to the other, they must increase by exactly 1 at every step. Reading the same path from the other end, they decrease by 1 at every step, so the same path can be described as either increasing or decreasing, depending on which end you start from.
The length of a path is its number of nodes. A single node is a path of length 1, so the answer is always at least 1.
Your function receives root as a TreeNode. 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.
root is in the range [1,105].Node.val ≤109The root `1` and its left child `2` differ by exactly `1`, giving a path of length `2`. The right child `3` isn't consecutive with anything, so `2` is the best.
The path `1-2-3` turns at the root: `1` to `2` is `+1` and `2` to `3` is `+1`, so reading the whole path from `1` to `3` increases by `1` at every step, giving a path of length `3`.
The single node `1` is trivially a path of length `1`.
Click "Run" to test with sample cases or "Submit" to run all tests.