0
class Solution:
    def searchPath(self,node,targetSum,path,result):
        if (not node.left) and (not node.right) and (targetSum==0):
            result.append(path)
        if (not node.left) and (not node.right) and (targetSum!=0):
            return 
        if node.left:
            path.append(node.left.val)
            self.searchPath(node.left,targetSum-node.left.val,path,result)
            path.pop()
        if node.right:
            path.append(node.right.val)
            self.searchPath(node.right,targetSum-node.right.val,path,result)
            path.pop()

        return result

The answer will be wrong. But if I change result.append(path) to result.append(path[:]) The answer will be correct. What's the difference?

0

1 Answer 1

1

The difference is that path[:] creates a shallow copy of path. Later mutating path in the following ifs does no longer change the path copy that was appended to result.

Appending path directly and later appending something to path changes the path that is already appended to result, effectively changing what result contains.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.