Python alternative solution with comments


  • 1
    Z
    def longestConsecutive(self, root):
    
        def dfs(root):
            l = dfs(root.left)+1 if root.left else 1        # must calculate if root.left exists
            if root.left and root.left.val != root.val+1:
                l = 1                                       # reset to 1 if numbers are not consecutive
            r = dfs(root.right)+1 if root.right else 1      # must calculate if root.right exists
            if root.right and root.right.val != root.val+1:
                r = 1                                       # reset to 1 if numbers are not consecutive
            self.depth = max(l,r,self.depth)
            return max(l,r)
    
        self.depth = 0
        if root:
            dfs(root)
        return self.depth

Log in to reply
 

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