Reputation: 13
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?
Upvotes: 0
Views: 66
Reputation: 57184
The difference is that path[:]
creates a shallow copy of path
. Later mutating path
in the following if
s 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.
Upvotes: 1