Python solution with generator


  • 0
    D
    class Solution:
        def pathSum(self, root, sum):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: List[List[int]]
            """
            def generate(path, root, sum):
                if root:
                    if not root.left and not root.right and root.val == sum:
                        yield path + [root.val]
                    for matched_path in generate(path + [root.val], root.left, sum-root.val):
                        yield matched_path
                    for matched_path in generate(path + [root.val], root.right, sum-root.val):
                        yield matched_path
            
            return list(generate([], root, sum))
    

Log in to reply
 

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