1. 题目
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]
示例 2:
输入:root = [1,2,3], targetSum = 5
输出:[]
示例 3:
输入:root = [1,2], targetSum = 0
输出:[]
提示:
树中节点总数在范围 [0, 5000] 内
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
2. 题解
2.1 解法1 DFS递归
from typing import Optional, List
class TreeNode:
def __init__(self, val=0, left=0, right=0):
self.val = val
self.left = left
self.right = right
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
ans = []
self.helper(root, targetSum, [], ans)
return ans
def helper(self, root: TreeNode, sum: int, path: List, ans: List):
if not root:
return
if root.left is None and root.right is None and sum == root.val:
path += [root.val]
ans.append(path)
self.helper(root.left, sum - root.val, path + [root.val], ans)
self.helper(root.right, sum - root.val, path + [root.val], ans)
2.2 DFS迭代 (差值)
from typing import Optional, List
class TreeNode:
def __init__(self, val=0, left=0, right=0):
self.val = val
self.left = left
self.right = right
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if not root:
return []
stack = [(root, [], targetSum - root.val)]
ans = []
while stack:
node, path, remain = stack.pop()
if node.left is None and node.right is None and remain == 0:
path += [node.val]
ans.append(path)
if node.left:
stack.append((node.left, path + [node.val], remain - node.left.val))
if node.right:
stack.append((node.right, path + [node.val], remain - node.right.val))
return ans
2.3 DFS迭代(累加)
from typing import Optional, List
class TreeNode:
def __init__(self, val=0, left=0, right=0):
self.val = val
self.left = left
self.right = right
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if not root:
return []
stack = [(root, [root.val], root.val)]
ans = []
while stack:
node, path, total = stack.pop()
if node.left is None and node.right is None and total == targetSum:
ans.append(path)
if node.left:
stack.append((node.left, path + [node.left.val], total + node.left.val))
if node.right:
stack.append((node.right, path + [node.right.val], total + node.right.val))
return ans