Leetcode 1254 Solution

This article provides solution to leetcode question 1254 (deepest-leaves-sum)

https://leetcode.com/problems/deepest-leaves-sum

Solution

# 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: TreeNode) -> int:
        max_depth = 0
        s = 0

        def dfs(node, depth):
            nonlocal s
            nonlocal max_depth

            if node is None:
                return

            if depth == max_depth:
                s += node.val
            elif depth > max_depth:
                max_depth = depth
                s = node.val

            dfs(node.left, depth + 1)
            dfs(node.right, depth + 1)

        dfs(root, 0)
        return s