- class Solution:
- def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
- ans=[]
- def fun(root,score,res):
- res.append(root.val)
- score+=root.val
- if score==targetSum and not root.left and not root.right:
- ans.append(res.copy())
- res.pop()
- return
- if root.left:
- fun(root.left,score,res)
- if root.right:
- fun(root.right,score,res)
- res.pop()
- if not root:
- return []
- fun(root,0,[])
- return ans
复制res:当找到一个有效的路径(即score == targetSum并且节点是叶子)时,使用res.copy()将res的副本附加到ans。这确保了附加的列表独立于将来对res的修改。
回溯:在处理节点之后(无论它是否指向有效路径),使用res.pop()从res中删除节点的值。这确保了res在遍历过程中正确地表示当前路径。