MediumTreeDepth-First SearchBinary Tree

Binary Tree Longest Consecutive Sequence

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now