LeetCode 298 [Binary Tree Longest Consecutive Sequence]

原题

给一个二叉树,求其中最长连续序列的长度

样例
比如,下面的树,最长序列为3->4->5,返回3

   1
    \
     3
    / \
   2   4
        \
         5

解题思路

  • 递归求解,分别向左右子树递归,判断当前值跟左儿子右儿子的值是否连续,连续则+1,否则重置为1
  • global变量res,不断更新

完整代码

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

        self.result = 0
        self.helper(root, 1)

        return self.result

    def helper(self, root, curLen):
        self.result = curLen if curLen > self.result else self.result
        if root.left:
            if root.left.val == root.val + 1:
                self.helper(root.left, curLen + 1)
            else:
                self.helper(root.left, 1)
        if root.right:
            if root.right.val == root.val + 1:
                self.helper(root.right, curLen + 1)
            else:
                self.helper(root.right, 1)

你可能感兴趣的:(LeetCode 298 [Binary Tree Longest Consecutive Sequence])