def sumPathHelper(root, target, curr, result):
if not root: return
target -= root.val
if root.left is None and root.right is None and target == 0:
#在代码片段里,并没有修改该iteration中的局部变量curr,因此,
#result.append(curr + #[root.val]) 中不需要list深拷贝
result.append(curr + [root.val])
if root.left:
sumPathHelper(root.left, target, curr + [root.val], result)
if root.right:
sumPathHelper(root.right, target, curr + [root.val], result)
def sumPathHelper2(root, target, curr, result):
if not root: return
target -= root.val
curr.extend([root.val])
if root.left is None and root.right is None and target == 0:
#代码片段中对curr进行了操作,如果使用result.append(curr)的话,result的值会根据curr的改变而被修改,
#因此需要list(curr)重新生成一个对象加入到result中,保证结果的正确
result.append(list(curr))
if root.left:
sumPathHelper2(root.left, target, curr, result)
if root.right:
sumPathHelper2(root.right, target, curr, result)
curr.pop()
迭代中的结果拷贝
最新推荐文章于 2024-11-04 21:51:40 发布