Binary Tree Longest Consecutive Sequence Problem
Description
LeetCode Problem 298.
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.
Constraints:
- The number of nodes in the tree is in the range
[1, 3 * 10^4]. -3 * 10^4 <= Node.val <= 3 * 10^4
Solution
Approach: Depth-First Search from the Bottom Up
A consecutive path only goes downward, from a parent to a child whose value is exactly one larger. So for every node we can ask: what is the longest consecutive path that starts here and goes down?
Let down(node) return that length. It is at least 1 (the node alone). If the left child exists and left.val == node.val + 1, the path can continue through it, giving down(left) + 1; the same holds for the right child. down(node) is the largest of these options. We compute the children first (post-order), and keep the best value seen over all nodes in best, because the longest path can start anywhere.
The tricky case: always recurse into both children, even a child that does not continue the current path. A new, longer path may start inside that subtree. In Example 1, 1 -> 3 is not consecutive, but the answer 3 -> 4 -> 5 lives below 3.
Also note that values must increase by one: in Example 2, 3 -> 2 -> 1 decreases and does not count, so the answer is 2 (from 2 -> 3).
Complexity: O(n) time, since each node is visited once. O(h) space for the recursion, where h is the height of the tree.
class Solution:
def longestConsecutive(self, root: Optional[TreeNode]) -> int:
best = 0
def down(node: Optional[TreeNode]) -> int:
"""Length of the longest consecutive path that starts at node and goes down."""
nonlocal best
if node is None:
return 0
# Visit both children, even one that does not continue the path.
left, right = down(node.left), down(node.right)
length = 1
if node.left and node.left.val == node.val + 1:
length = max(length, left + 1)
if node.right and node.right.val == node.val + 1:
length = max(length, right + 1)
best = max(best, length)
return length
down(root)
return best