leetcode 1302. Deepest Leaves Sum(python)

描述

Given the root of a binary tree, return the sum of values of its deepest leaves.

Example 1:

avatar

Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15

Example 2:

Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 19

Note:

The number of nodes in the tree is in the range [1, 104].
1 <= Node.val <= 100

解析

根据题意,其实就是算最底层的树的节点的值的和,需要用一个字典来记录,key 为深度,value 为该深度的树的所有节点的数值,DFS 遍历之后得到 res ,然后计算最后一层的和即可。

解答

class Solution(object):
    def deepestLeavesSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        res = {}
        def lastLevel(root, res, count):
            if not root:
                return
            if count not in res:
                res[count] = []
            res[count].append(root.val)
            if root.left:
                lastLevel(root.left, res, count + 1)
            if root.right:
                lastLevel(root.right, res, count + 1)
        lastLevel(root, res, 0)
        return sum(res[max(res.keys())])

运行结果

Runtime: 92 ms, faster than 79.13% of Python online submissions for Deepest Leaves Sum.
Memory Usage: 20.8 MB, less than 79.37% of Python online submissions for Deepest Leaves Sum.

原题链接:https://leetcode.com/problems/deepest-leaves-sum

您的支持是我最大的动力

猜你喜欢

转载自blog.csdn.net/wang7075202/article/details/115267412