-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode 1302 - deepest leaves sum.py
36 lines (29 loc) · 1.04 KB
/
leetcode 1302 - deepest leaves sum.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
# deepest leaves sum | leetcode 1302 | https://leetcode.com/problems/deepest-leaves-sum/
# method: dfs
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def deepestLeavesSum(self, root) -> int:
result = 0
maxHeight = 0
# dfs
def dfs(node, currHeight):
nonlocal result, maxHeight
if node is None:
return
# reset if current height is not max
if currHeight > maxHeight:
result = 0
maxHeight = currHeight
# add to sum if current height is max
if currHeight == maxHeight:
result += node.val
# recursively traverse left and right subtrees
dfs(node.left, currHeight + 1)
dfs(node.right, currHeight + 1)
dfs(root, 0)
return result