NeetCode #400LC-298MediumTreesNC Algo100
← Back to All Problems#400 · #298 · Binary Tree Longest Consecutive Sequence(二叉树最长连续序列)
📌 Problem Statement & Constraints
Given the root of a binary tree, find the length of the longest consecutive path: a path where each node's value is exactly one greater than its parent's. The path must follow parent-child links and may go only downward. Constraints: the number of nodes is in
[1, 3 * 10^4].💡 Core Algorithmic Approaches
- Do a DFS carrying two things: the parent node and the current consecutive length.
- At each node, the length is
parent_length + 1if the value is exactlyparent.val + 1, otherwise reset to 1. - The answer is the maximum length seen anywhere.
- This is a top-down DP with no memoisation needed, since each node has a unique parent.
💻 Benchmark Python3 Implementation
class Solution:
def longestConsecutive(self, root: Optional[TreeNode]) -> int:
def dfs(node: Optional[TreeNode], parent: Optional[TreeNode], length: int) -> int:
if not node:
return length
if parent and node.val == parent.val + 1:
length += 1 # extend the run
else:
length = 1 # restart
return max(length,
dfs(node.left, node, length),
dfs(node.right, node, length))
return dfs(root, None, 0)⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): every node is visited once.
💾 Space Complexity
O(h) for the recursion stack.
⚠️ Interview Pitfalls & Follow-ups
- Comparing with
>=: the values must differ by exactly 1. - Passing the length without resetting: a broken run would keep accumulating.
- Allowing the path to go upward: consecutive paths must be strictly downward.
- Forgetting the
parent is Nonecase at the root: the root always starts a run of length 1.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Trees Problems
中文速览与面试要点
二叉树最长连续序列
给你一棵指定的二叉树的根节点 root,请你计算其中 最长连续序列路径 的长度。最长连续序列路径是 依次递增 1 的路径,路径可以起始于树中任何节点,终止于树中任何节点。该路径可以经过父节点和子节点,但 只能 沿着父节点到子节点的方向(即从上到下)。约束:树中节点数目在范围 [1, 3 × 10^4] 内;-3 × 10^4 ≤ Node.val ≤ 3 × 10^4。
核心要点
- 前序遍历 + 传递长度(标准解) :递归时传递「以父节点结尾的连续序列长度」与父节点引用,若当前节点值等于父节点值加一,则长度加一,否则重置为 1。
- 为什么必须从上到下 :路径方向固定(父 → 子),因此只需在向下递归时传递信息,无需返回值。
- 与 549 的区别 :本题路径必须 向下 (只能递增);549 允许「先增后减」的折线路径。
- 复杂度 :O(n) 时间、O(h) 空间。
常见陷阱
- 用返回值累加 :本题路径只能向下,返回值方案不适用(那适合 549 的折线路径)。
- 忘记在断开时重置为 1 :会导致长度一直累加。
- 误以为可以「先增后减」 :本题只允许递增且向下,折线路径属于 549 题。
- 根节点处理 : parent 为 None,长度应为 1,本解通过 else 分支处理。
参考实现
class Solution:
def longestConsecutive(self, root: 'TreeNode') -> int:
best = 0
def dfs(node, parent, length: int) -> None:
"""length 表示以 parent 结尾的连续序列长度。"""
nonlocal best
if not node:
return
# 若与父节点连续则累加,否则重新开始
if parent and node.val == parent.val + 1:
length += 1
else:
length = 1
if length > best:
best = length
dfs(node.left, node, length)
dfs(node.right, node, length)
dfs(root, None, 0)
return best