Leetcode 113 - Path Sum II
Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where each path's sum equals targetSum.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
if not root: return []
res = []
def dfs(node, total = 0, path = []):
if not node: return
path.append(node.val)
total += node.val
if not node.left and not node.right and total == targetSum:
res.append(list(path))
else:
dfs(node.left, total, path)
dfs(node.right, total, path)
total -= path.pop()
dfs(root)
return res
Why we have to use res.append(list(path))
rather than use res.append(path)
?
If we only append path
into res, it would only append empty list into res
.
This is a subtle Python issue. When you use a default parameter like that (in the def dfs
line), it captures that default object at definition time. So, every time that function runs, path
is set to the SAME empty list. If you change that list, everyone with a reference to it sees the change. I believe they use list(path) to make a copy of that list, rather than store a link to the common list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.