113. 路径总和 II(迭代注意pop,copy()的使用)

113. 路径总和 II

  1. class Solution:
  2.     def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
  3.         ans=[]
  4.         def fun(root,score,res):
  5.             res.append(root.val)
  6.             score+=root.val
  7.             if score==targetSum and not root.left and not root.right:
  8.                 ans.append(res.copy())
  9.                 res.pop()
  10.                 return
  11.             if root.left:
  12.                 fun(root.left,score,res)
  13.             if root.right:
  14.                 fun(root.right,score,res)
  15.             res.pop()
  16.         if not root:
  17.             return []
  18.         fun(root,0,[])
  19.         return ans

复制res:当找到一个有效的路径(即score == targetSum并且节点是叶子)时,使用res.copy()将res的副本附加到ans。这确保了附加的列表独立于将来对res的修改。

回溯:在处理节点之后(无论它是否指向有效路径),使用res.pop()从res中删除节点的值。这确保了res在遍历过程中正确地表示当前路径。

发表评论