Skip to content

Commit e8a4b85

Browse files
committed
Binary Tree Minimum Path Sum
1 parent f02de34 commit e8a4b85

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Apple/Problem#580.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
Given a binary tree, find a minimum path sum from root to a leaf.
3+
For example, the minimum path in this tree is [10, 5, 1, -1], which has sum 15.
4+
10
5+
/ \
6+
5 5
7+
\ \
8+
2 1
9+
/
10+
-1
11+
"""
12+
class Solution:
13+
def minPathSum(self, root: TreeNode) -> int:
14+
self.ans = float('inf')
15+
16+
def helper(root, cur_sum=0):
17+
if not root:
18+
self.ans = min(self.ans, cur_sum)
19+
return 0
20+
21+
cur_sum += root.val
22+
l = helper(root.left, cur_sum)
23+
r = helper(root.right, cur_sum)
24+
cur_sum -= root.val
25+
26+
helper(root)
27+
28+
return self.ans

0 commit comments

Comments
 (0)