题目
解法
DFS。但是这里要注意python的一些特性。
python传参传对象,可变对象可变,不可变对象不可变
class Solution:
def pathSum(self, root: TreeNode, target: int) -> List[List[int]]:
res, cur = [], []
def dfs(root, tar):
if not root: return
cur.append(root.val)
if root.left is None and root.right is None and root.val==tar:
res.append(list(cur)) # 这个域里,要用list()将cur转成值,不然,cur是一个可变对象,后面cur变化,res也会变
else:
dfs(root.left, tar-root.val)
dfs(root.right, tar-root.val)
cur.pop(-1)
dfs(root, target)
return res