Skip to content

Commit 7d2f575

Browse files
committed
feat: [437] Path Sum III
1 parent 7e0dbdc commit 7d2f575

4 files changed

Lines changed: 47 additions & 1 deletion

File tree

src/binary_tree/dfs/path_sum_iii/__init__.py

Whitespace-only changes.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from typing import Optional
2+
from collections import defaultdict
3+
from structures import TreeNode
4+
5+
6+
class Solution:
7+
def dfs(self, root: Optional[TreeNode], current_sum: int, target_sum: int):
8+
if root is None:
9+
return 0
10+
11+
current_sum += root.val
12+
count: int = self.cache[current_sum - target_sum]
13+
self.cache[current_sum] += 1
14+
15+
count += self.dfs(root.left, current_sum, target_sum)
16+
count += self.dfs(root.right, current_sum, target_sum)
17+
18+
self.cache[current_sum] -= 1
19+
20+
return count
21+
22+
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
23+
self.cache = defaultdict(int)
24+
self.cache[0] = 1
25+
return self.dfs(root, 0, targetSum)

structures/tree.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
class TreeNode:
2-
def __init__(self, val: int = 0, left: int | None = None, right: int | None = None):
2+
def __init__(
3+
self,
4+
val: int = 0,
5+
left: "TreeNode | None" = None,
6+
right: "TreeNode | None" = None,
7+
):
38
self.val = val
49
self.left = left
510
self.right = right

tests/test_path_sum_iii.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import pytest
2+
from src.binary_tree.dfs.path_sum_iii.solution import Solution
3+
from test_utils import TreeBuilder
4+
5+
6+
@pytest.mark.parametrize(
7+
"root, target_sum, expected",
8+
[
9+
([10, 5, -3, 3, 2, None, 11, 3, -2, None, 1], 8, 3),
10+
([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, 5, 1], 22, 3),
11+
],
12+
)
13+
def test_leaf_similar(root: list, target_sum: int, expected: int):
14+
root = TreeBuilder.from_list(root)
15+
solution = Solution()
16+
assert solution.pathSum(root, target_sum) == expected

0 commit comments

Comments
 (0)