-
Notifications
You must be signed in to change notification settings - Fork 0
/
135.py
72 lines (53 loc) · 1.55 KB
/
135.py
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
"""
Problem:
Given a binary tree, find a minimum path sum from root to a leaf.
For example, the minimum path in this tree is [10, 5, 1, -1], which has sum 15.
10
/ \
5 5
\ \
2 1
/
-1
"""
from typing import List, Tuple
from DataStructures.Tree import BinaryTree, Node
def minimum_path_sum_helper(node: Node) -> Tuple[int, List[int]]:
left_sum, left = None, None
right_sum, right = None, None
if node.left:
left_sum, left = minimum_path_sum_helper(node.left)
if node.right:
right_sum, right = minimum_path_sum_helper(node.right)
# generating the minimum path sum
if not left and not right:
return node.val, [node.val]
elif left and not right:
return (left_sum + node.val), left + [node.val]
elif right and not left:
return (right_sum + node.val), right + [node.val]
return min(
((left_sum + node.val), left + [node.val]),
((right_sum + node.val), right + [node.val]),
key=lambda x: x[0],
)
def minimum_path_sum(tree: BinaryTree) -> List[int]:
if not tree.root:
raise ValueError("Empty Tree")
_, path = minimum_path_sum_helper(tree.root)
return path[::-1]
if __name__ == "__main__":
tree = BinaryTree()
tree.root = Node(10)
tree.root.left = Node(5)
tree.root.right = Node(5)
tree.root.left.right = Node(2)
tree.root.right.right = Node(1)
tree.root.right.right.left = Node(-1)
print(tree)
print(minimum_path_sum(tree))
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(n)
"""