Binary Tree Longest Consecutive Sequence — LeetCode 298 Python Solution
- Problem
- #298
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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.
Example
- 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.
Python solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def longestConsecutive(self, root: Optional[TreeNode]) -> int:
def dfs(root: Optional[TreeNode]) -> int:
if root is None:
return 0
l = dfs(root.left) + 1
r = dfs(root.right) + 1
if root.left and root.left.val - root.val != 1:
l = 1
if root.right and root.right.val - root.val != 1:
r = 1
t = max(l, r)
nonlocal ans
ans = max(ans, t)
return t
ans = 0
dfs(root)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 298. Binary Tree Longest Consecutive Sequence is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 298. Binary Tree Longest Consecutive Sequence?
- LeetCode 298. Binary Tree Longest Consecutive Sequence is rated Medium on LeetCode.
- What is the time complexity of LeetCode 298. Binary Tree Longest Consecutive Sequence?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 298. Binary Tree Longest Consecutive Sequence?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 298. Binary Tree Longest Consecutive Sequence cover?
- LeetCode 298. Binary Tree Longest Consecutive Sequence is tagged Tree, Depth-First Search and Binary Tree on LeetCode.
- Is LeetCode 298. Binary Tree Longest Consecutive Sequence a premium problem?
- Yes. LeetCode 298. Binary Tree Longest Consecutive Sequence is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.