Python solution from contest

  • 1

    My contest solution with minimal cleanup:

    def pathSum(self, root, sum2):
        res = [0]
        def helper2(path, sum2):
            prev = path[-1]
            if prev == sum2: res[0] += 1
            for i in range(len(path)-2, -1, -1):
                prev += path[i]
                if prev == sum2: res[0] += 1
        def helper(node, sum2, path):
            if not node: return
            new_path = path + [node.val]
            helper2(new_path, sum2)
            helper(node.left, sum2, new_path)
            helper(node.right, sum2, new_path)
        helper(root, sum2, [])
        return res[0]

Log in to reply

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