Skip to content

Commit 25757e6

Browse files
CaedenPHpre-commit-ci[bot]cclauss
authored
Binary tree path sum (#7748)
* feat: Implement binary tree path sum (#7135) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update data_structures/binary_tree/binary_tree_path_sum.py Co-authored-by: Christian Clauss <[email protected]> * refactor: Rename `dfs` to `depth_first_search` Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <[email protected]>
1 parent de3271e commit 25757e6

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
"""
2+
Given the root of a binary tree and an integer target,
3+
find the number of paths where the sum of the values
4+
along the path equals target.
5+
6+
7+
Leetcode reference: https://leetcode.com/problems/path-sum-iii/
8+
"""
9+
10+
from __future__ import annotations
11+
12+
13+
class Node:
14+
"""
15+
A Node has value variable and pointers to Nodes to its left and right.
16+
"""
17+
18+
def __init__(self, value: int) -> None:
19+
self.value = value
20+
self.left: Node | None = None
21+
self.right: Node | None = None
22+
23+
24+
class BinaryTreePathSum:
25+
r"""
26+
The below tree looks like this
27+
10
28+
/ \
29+
5 -3
30+
/ \ \
31+
3 2 11
32+
/ \ \
33+
3 -2 1
34+
35+
36+
>>> tree = Node(10)
37+
>>> tree.left = Node(5)
38+
>>> tree.right = Node(-3)
39+
>>> tree.left.left = Node(3)
40+
>>> tree.left.right = Node(2)
41+
>>> tree.right.right = Node(11)
42+
>>> tree.left.left.left = Node(3)
43+
>>> tree.left.left.right = Node(-2)
44+
>>> tree.left.right.right = Node(1)
45+
46+
>>> BinaryTreePathSum().path_sum(tree, 8)
47+
3
48+
>>> BinaryTreePathSum().path_sum(tree, 7)
49+
2
50+
>>> tree.right.right = Node(10)
51+
>>> BinaryTreePathSum().path_sum(tree, 8)
52+
2
53+
"""
54+
55+
target: int
56+
57+
def __init__(self) -> None:
58+
self.paths = 0
59+
60+
def depth_first_search(self, node: Node | None, path_sum: int) -> None:
61+
if node is None:
62+
return
63+
64+
if path_sum == self.target:
65+
self.paths += 1
66+
67+
if node.left:
68+
self.depth_first_search(node.left, path_sum + node.left.value)
69+
if node.right:
70+
self.depth_first_search(node.right, path_sum + node.right.value)
71+
72+
def path_sum(self, node: Node | None, target: int | None = None) -> int:
73+
if node is None:
74+
return 0
75+
if target is not None:
76+
self.target = target
77+
78+
self.depth_first_search(node, node.value)
79+
self.path_sum(node.left)
80+
self.path_sum(node.right)
81+
82+
return self.paths
83+
84+
85+
if __name__ == "__main__":
86+
import doctest
87+
88+
doctest.testmod()

0 commit comments

Comments
 (0)