Skip to content

Commit d19ba25

Browse files
Add Py solution to LC1302
1 parent c8450fc commit d19ba25

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

LC1302-Deepest-Leaves-Sum.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
"""
2+
Given the root of a binary tree, return the sum of values
3+
of its deepest leaves.
4+
5+
Example 1:
6+
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
7+
Output: 15
8+
9+
Example 2:
10+
Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
11+
Output: 19
12+
13+
14+
Constraints:
15+
(*) The number of nodes in the tree is in the range [1, 10^4].
16+
(*) 1 <= Node.val <= 100
17+
"""
18+
from TreeNode import TreeNode
19+
20+
# Definition for a binary tree node.
21+
# class TreeNode:
22+
# def __init__(self, val=0, left=None, right=None):
23+
# self.val = val
24+
# self.left = left
25+
# self.right = right
26+
class Solution:
27+
def deepestLeavesSum(self, root: TreeNode) -> int:
28+
if root is None:
29+
return 0
30+
31+
level_new = [root, ]
32+
while level_new:
33+
level = list(level_new)
34+
level_new = list()
35+
for node in level:
36+
if node.left is not None:
37+
level_new.append(node.left)
38+
if node.right is not None:
39+
level_new.append(node.right)
40+
return sum(node.val for node in level)
41+
42+
43+
if __name__ == "__main__":
44+
import run_tests
45+
46+
correct_answers = [
47+
[[1,2,3,4,5,None,6,7,None,None,None,None,8], 15],
48+
[[6,7,8,2,7,1,3,9,None,1,4,None,None,None,5], 19]
49+
]
50+
for i in range(len(correct_answers)):
51+
correct_answers[i][0] = TreeNode.to_treenode(correct_answers[i][0])
52+
print(f"Running tests for deepestLeavesSum")
53+
run_tests.run_tests(Solution().deepestLeavesSum, correct_answers)

0 commit comments

Comments
 (0)