---
# System prepended metadata

title: 0549. Binary Tree Longest Consecutive Sequence II
tags: [Leetcode, Tree, Medium]

---

# 0549. Binary Tree Longest Consecutive Sequence II
###### tags: `Leetcode` `Medium` `Tree`
Link: https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/description/
## Code
```python=
class Solution:
    def longestConsecutive(self, root: Optional[TreeNode]) -> int:
        def dfs(root):
            if root is None: return 0,0
            inr, dcr = 1, 1
            if root.left is not None:
                linr, ldcr = dfs(root.left)
                if root.val == root.left.val+1:
                    dcr = ldcr+1
                elif root.val == root.left.val-1:
                    inr = linr+1
            if root.right is not None:
                rinr, rdcr = dfs(root.right)
                if root.val == root.right.val+1:
                    dcr = max(dcr, rdcr+1)
                elif root.val == root.right.val-1:
                    inr = max(inr, rinr+1)
            ans[0] = max(ans[0], dcr+inr-1)
            return inr, dcr
        
        ans = [0]
        dfs(root)
        return ans[0]
```