-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.py
30 lines (24 loc) · 975 Bytes
/
solution.py
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
29
30
from collections import deque
from typing import List, Optional
# 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]]:
if not root:
return []
paths = []
queue = deque([[root, [root.val], targetSum-root.val]])
while queue:
node, path, current_sum = queue.popleft()
left_node, right_node = node.left, node.right
if not left_node and not right_node and current_sum == 0:
paths.append(path)
if left_node:
queue.append([left_node, path+[left_node.val], current_sum-left_node.val])
if right_node:
queue.append([right_node, path+[right_node.val], current_sum-right_node.val])
return paths