forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath_sum.py
More file actions
97 lines (76 loc) · 2.58 KB
/
path_sum.py
File metadata and controls
97 lines (76 loc) · 2.58 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
"""
Path Sum
Given a binary tree and a target sum, determine if the tree has a root-to-leaf
path such that adding up all values along the path equals the given sum.
Provides recursive, DFS, and BFS solutions.
Reference: https://en.wikipedia.org/wiki/Binary_tree
Complexity:
Time: O(n)
Space: O(n)
"""
from __future__ import annotations
from collections import deque
from algorithms.tree.tree import TreeNode
def has_path_sum(root: TreeNode | None, sum: int) -> bool:
"""Check if a root-to-leaf path with the given sum exists (recursive).
Args:
root: The root of the binary tree.
sum: The target sum.
Returns:
True if such a path exists, False otherwise.
Examples:
>>> has_path_sum(None, 0)
False
"""
if root is None:
return False
if root.left is None and root.right is None and root.val == sum:
return True
sum -= root.val
return has_path_sum(root.left, sum) or has_path_sum(root.right, sum)
def has_path_sum2(root: TreeNode | None, sum: int) -> bool:
"""Check if a root-to-leaf path with the given sum exists (DFS with stack).
Args:
root: The root of the binary tree.
sum: The target sum.
Returns:
True if such a path exists, False otherwise.
Examples:
>>> has_path_sum2(None, 0)
False
"""
if root is None:
return False
stack: list[tuple[TreeNode, int]] = [(root, root.val)]
while stack:
node, val = stack.pop()
if node.left is None and node.right is None and val == sum:
return True
if node.left is not None:
stack.append((node.left, val + node.left.val))
if node.right is not None:
stack.append((node.right, val + node.right.val))
return False
def has_path_sum3(root: TreeNode | None, sum: int) -> bool:
"""Check if a root-to-leaf path with the given sum exists (BFS with queue).
Args:
root: The root of the binary tree.
sum: The target sum.
Returns:
True if such a path exists, False otherwise.
Examples:
>>> has_path_sum3(None, 0)
False
"""
if root is None:
return False
queue: deque[tuple[TreeNode, int]] = deque([(root, sum - root.val)])
while queue:
node, val = queue.popleft()
if node.left is None and node.right is None and val == 0:
return True
if node.left is not None:
queue.append((node.left, val - node.left.val))
if node.right is not None:
queue.append((node.right, val - node.right.val))
return False