Binary Tree Longest Consecutive Sequence
1 approach, code in every language
Problem description
You are given the root of a binary tree. A consecutive sequence is a path that moves downward from a parent to a child where each step increases the value by exactly one.
The path must go strictly top-to-bottom (a node connects only to its child, never back up through a parent) and cannot skip or reverse direction. Return the length of the longest such consecutive-increasing path.
Example 1
Input: root = [1,null,3,2,4,null,null,null,5]
Output: 3
The longest consecutive path is 3 -> 4 -> 5, which has length 3.
Example 2
Input: root = [2,null,3,2,null,1]
Output: 2
2 -> 3 forms a consecutive increasing run of length 2; the 3 -> 2 -> 1 branch decreases, so it does not count.
Constraints
The number of nodes in the tree is in the range [1, 3 * 10^4].-3 * 10^4 <= Node.val <= 3 * 10^4
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free