Python simple solution, use a global var instead of passing more parameters


  • 0
    P
    class Solution(object):
        def longestConsecutive(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            self.res = 0
            
            def travel(root):
                if not root:
                    return 0
                left = travel(root.left) if root.left else 1
                left += 1 if (root.left and root.val+1 == root.left.val) else -left+1
                right = travel(root.right) if root.right else 1
                right += 1 if (root.right and root.val+1 == root.right.val) else -right+1
                val = max(left, right)
                self.res = max(val, self.res)
                return val
                
            travel(root)
            return self.res
    

    -left+1 and -right+1 is just a trick to make sure left=1 and right=1 when there is left or right child but its value is not equal to the its parent's value (root.val != root.left.val) and to save lines


Log in to reply
 

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