Leetcode 1302:层数最深叶子节点的和(超详细的解法!!!)
in leetcode with 0 comment

Leetcode 1302:层数最深叶子节点的和(超详细的解法!!!)

in leetcode with 0 comment

给你一棵二叉树,请你返回层数最深的叶子节点的和。

示例:

输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
输出:15

提示:

解题思路

思路非常简单,就是通过bfs遍历整颗二叉树,然后返回最后一层的和。

class Solution:
    def deepestLeavesSum(self, root: TreeNode) -> int:
        q, res = [root], 0
        while q:
            res, n = 0, len(q)
            for _ in range(n):
                cur = q.pop(0)
                res += cur.val
                if cur.left:
                    q.append(cur.left)
                if cur.right:
                    q.append(cur.right)
        return res

一个简洁的写法:

class Solution:
    def deepestLeavesSum(self, root: TreeNode) -> int:
        l = [root]
        while l:
            pre, l = l, [child for p in l for child in [p.left, p.right] if child]
        return sum(node.val for node in pre)

reference:

https://leetcode.com/problems/deepest-leaves-sum/discuss/463239/Python-Level-Traversal

我将该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

「如果我的文章对你有很大帮助,那么不妨~!」

coordinate

谢谢老板O(∩_∩)O~

使用微信扫描二维码完成支付

Responses