Binary Tree Longest Consecutive Sequence

Problem: Binary Tree Longest Consecutive Sequence

We use first assume the consecutive sequence start at this point if no sequence inherited from parent then do depth-first search on its left and right children. Extend the sequence if they are consecutive.

Code in Python:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def longestConsecutive(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root: return 0

        self.ans = 0

        def dfs(node, length):
            self.ans = max(length, self.ans)
            if node.left:
                if node.left.val == node.val + 1: dfs(node.left, length+1)
                else: dfs(node.left, 1)
            if node.right:
                if node.right.val == node.val + 1: dfs(node.right, length+1)
                else: dfs(node.right, 1)

        dfs(root, 1)
        return self.ans

results matching ""

    No results matching ""