Simple python solution


  • 0
    Z
    # 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
            """
            # 
            # we need to run the helper() function
            #  
            maxVal = [0]
            count = [0]
            def helper(root):
                if not root:
                    maxLen=0
                #elif not root.left and not root.right:
                #    maxLen=1
                else:
                    maxLen = 1
                    left = helper(root.left)
                    right = helper(root.right)
                    maxLen += max(left if left and root.val+1==root.left.val else 0,right if right and root.val+1==root.right.val else 0)
                maxVal[0]=max(maxVal[0],maxLen)
                return maxLen
            helper(root)
            return maxVal[0]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.