解题思路:
此题与112题相似。区别在于:
1.递归函数的终止条件不需要返回值。
2.需要在终止条件处,添加result.append(res[:])逻辑
注意:
1.result.append(res) 与 result.append(res[:])的功能是不同的
后者将res的副本拷贝一份append到result中;前者只是将res指针放入result中,这样的话,随着res在递归深入回溯的过程中不断变化,result数组的元素也会不断变化。所以选取后者
2.注意
result = []
res = [root.val]
isornot(root, targetSum - root.val, res)
三行是并列的,可以放在主函数pathSum中并列运行,在isornot()中可以调用local variable result,所以不需要单独创建self.result
- # 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: Optional[TreeNode], targetSum: int) -> List[List[int]]:
- def isornot(root: Optional[TreeNode], targetSum: int, res: List[int]) -> List[List[int]]:
-
- if (not root.left) and (not root.right) and targetSum == 0:
- result.append(res[:])
- return
- if (not root.left) and (not root.right):
- return
-
- if root.left:
- res.append(root.left.val)
- isornot(root.left, targetSum - root.left.val, res)
- res.pop()
- if root.right:
- res.append(root.right.val)
- isornot(root.right, targetSum - root.right.val, res)
- res.pop()
-
-
- if root == None:
- return []
- else:
- result = []
- res = [root.val]
- isornot(root, targetSum - root.val, res)
- return result