Can anyone take a look and fix my code ?


  • 0
    Z
    class Solution(object):
        def pathSum(self, root, sum):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: List[List[int]]
            """
            res = []
            if not root:
                return res
        
            path = [root.val]
            self.helper(root,sum-root.val,path,res)
            return res
        
        def helper(self, root, sum, path, res):
            if not root:
                return
            
            if not root.left and not root.right and sum == 0:
                res.append(path)
    
                return
            
            if root.left:
                path.append(root.left.val)
                self.helper(root.left,sum-root.left.val,path,res)
                path.pop()
    
            if root.right:
                path.append(root.right.val)
                self.helper(root.right,sum-root.right.val,path,res)
                path.pop()
    

    How to fix my code ?
    input:

    [5,4,7,3,null,2,null,-1,null,9]
    23

    Answer [[5]]
    Expected answer [[5,7,2,9]]


  • 0

    res.append(path) appends the list that will be changed afterwards. Append a copy of path to prevent that.


Log in to reply
 

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