给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
遍历所有的路径找出合为目标的即可
依据题意 选择先序遍历
def pathSum(self, root: Optional[TreeNode], targetSum: int):
pathes = []
res = []
def deep(root):
nonlocal pathes
nonlocal res
nonlocal targetSum
if root is None:
return
pathes.append(root.val)
if root.val == 4:
print(root.left, root.right)
if root.left is None and root.right is None:
if sum(pathes) == targetSum:
res.append([p for p in pathes])
pathes.pop()
return
deep(root.left)
deep(root.right)
pathes.pop()
deep(root)
return res