Member-only story

Leetcode 298: Binary Tree Longest Consecutive Sequence (M)

Kanghui Liu
4 min readJan 31, 2025

Follow along this binary tree series and master the binary tree problem

Problem

cn link, com link

Given the root of a binary tree, return the length of the longest consecutive sequence path.

A consecutive sequence path is a path where the values increase by one along the path.

Note that the path can start at any node in the tree, and you cannot go from a node to its parent in the path.

Example 1:

Input: root = [1,null,3,2,4,null,null,null,5]
Output: 3
Explanation: Longest consecutive sequence path is 3-4-5, so return 3.

Example 2:

Input: root = [2,null,3,2,null,1]
Output: 2
Explanation: Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.

Thought Process

DFS with Base Case

The problem is looking for the longest path, so we want to explore a branch as far as possible = DFS

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Kanghui Liu
Kanghui Liu

Written by Kanghui Liu

Software Developer & Airbnb Host & Dog Mum & Gardener

No responses yet

Write a response