|
| 1 | +""" |
| 2 | +113. Path Sum II |
| 3 | +Medium |
| 4 | +Backtracking | Tree | Depth-First Search | Binary Tree |
| 5 | +--- |
| 6 | +Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values |
| 7 | + in the path equals targetSum. Each path should be returned as a list of the node values, not node references. |
| 8 | +
|
| 9 | +A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children. |
| 10 | +
|
| 11 | +Example 1: |
| 12 | +Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 |
| 13 | +Output: [[5,4,11,2],[5,8,4,5]] |
| 14 | +Explanation: There are two paths whose sum equals targetSum: |
| 15 | +5 + 4 + 11 + 2 = 22 |
| 16 | +5 + 8 + 4 + 5 = 22 |
| 17 | +
|
| 18 | +Example 2: |
| 19 | +Input: root = [1,2,3], targetSum = 5 |
| 20 | +Output: [] |
| 21 | +
|
| 22 | +Example 3: |
| 23 | +Input: root = [1,2], targetSum = 0 |
| 24 | +Output: [] |
| 25 | +
|
| 26 | +Constraints: |
| 27 | +The number of nodes in the tree is in the range [0, 5000]. |
| 28 | +-1000 <= Node.val <= 1000 |
| 29 | +-1000 <= targetSum <= 1000 |
| 30 | +""" |
| 31 | + |
| 32 | +from typing import Optional, List |
| 33 | + |
| 34 | + |
| 35 | +# Definition for a binary tree node. |
| 36 | +class TreeNode: |
| 37 | + def __init__(self, val=0, left=None, right=None): |
| 38 | + self.val = val |
| 39 | + self.left = left |
| 40 | + self.right = right |
| 41 | + |
| 42 | + |
| 43 | +# O(n ^ 2) time | O(H) space |
| 44 | +class Solution: |
| 45 | + def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]: |
| 46 | + def checkSum(root: TreeNode, sum: int, path: List[int]) -> bool: |
| 47 | + if not root: |
| 48 | + return |
| 49 | + |
| 50 | + path.append(root.val) |
| 51 | + sum -= root.val |
| 52 | + |
| 53 | + if root.right == None and root.left == None: |
| 54 | + if sum == 0: |
| 55 | + res.append(path.copy()) |
| 56 | + else: |
| 57 | + checkSum(root.left, sum, path) or checkSum( |
| 58 | + root.right, sum, path) |
| 59 | + path.pop() |
| 60 | + |
| 61 | + res = [] |
| 62 | + checkSum(root, targetSum, []) |
| 63 | + return res |
0 commit comments