Binary Tree Longest Consecutive Sequence

这道题的题意不太好理解,这里要的是从上到下的最长上升序列,下降不考虑,一般来说从上到下的思考方式比较自然

# 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):
    count = 0

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

        self.helper(root.left, root.val, 1)
        self.helper(root.right, root.val, 1)
        return self.count

    def helper(self, root, parentVal, step):
        if not root:
            self.count = max(self.count, step)
            return 

        if root.val == parentVal + 1:
            self.count = max(self.count, step + 1)
            self.helper(root.left, root.val, step + 1)
            self.helper(root.right, root.val, step + 1)
        else:
            self.helper(root.left, root.val, 1)
            self.helper(root.right, root.val, 1)

results matching ""

    No results matching ""