题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是给一个二叉树和目标和 target,求所有二叉树中从根到叶子路径和刚好为 target 的路径。

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 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]]:
ans = []
cur = []
def dfs(root: Optional[TreeNode], cur_sum: int):
if not root:
return
nonlocal cur
cur_sum += root.val
cur.append(root.val)

if not root.left and not root.right and cur_sum == targetSum:
nonlocal ans
ans.append(cur.copy())
else:
dfs(root.left, cur_sum)
dfs(root.right, cur_sum)

cur.pop()
dfs(root, 0)
return ans