15 line Python DFS Recursive Solution

  • 0
        def longestConsecutive(self, root):
            :type root: TreeNode
            :rtype: int
            def recurse(curr_len, root):
                if not root:
                    return 0
                curr_len += 1
                left_len = 0
                right_len = 0
                if root.left:
                    if root.left.val == root.val+1:
                        left_len = recurse(curr_len, root.left)
                        left_len = recurse(0, root.left)
                if root.right:
                    if root.right.val == root.val+1:
                        right_len = recurse(curr_len, root.right)
                        right_len = recurse(0, root.right)
                len = max(curr_len, left_len, right_len)
                return len
            return recurse(0, root)

Log in to reply

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