LC 0298 [M] Binary Tree Longest Consecutive Sequence - ALawliet/algorithms GitHub Wiki

as straightforward as it feels

# 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):
        self.longest = 0
        
        def preorder(root, count, target):
            if not root:
                return

            if root.val == target:
                count += 1
            else:
                count = 1

            self.longest = max(self.longest, count)

            preorder(root.left, count, root.val+1)
            preorder(root.right, count, root.val+1)
        
        preorder(root, 0, 0)
        return self.longest