Skip to content

Commit 7303f81

Browse files
committed
feat: Basic binary tree implementation (TheAlgorithms#7135)
1 parent 88766e9 commit 7303f81

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
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 data variable and pointers to Nodes to its left and right.
16+
"""
17+
18+
def __init__(self, data: int) -> None:
19+
self.data = data
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(tree).path_sum(8)
47+
3
48+
>>> BinaryTreePathSum(tree).path_sum(7)
49+
1
50+
>>> tree.right.right = Node(10)
51+
>>> BinaryTreePathSum(tree).path_sum(8)
52+
2
53+
"""
54+
55+
def __init__(self, tree: Node) -> None:
56+
self.tree = tree
57+
58+
def depth_first_search(self, node: Node | None) -> int:
59+
"""
60+
61+
"""
62+
if node is None:
63+
return 0
64+
65+
return self.depth_first_search(node)
66+
67+
def path_sum(self, target: int) -> int:
68+
"""
69+
70+
71+
"""
72+
return self.depth_first_search(self.tree, target)
73+
74+
75+
if __name__ == "__main__":
76+
import doctest
77+
78+
doctest.testmod()

0 commit comments

Comments
 (0)