LeetCode 1302 Deepest Leaves Sum (Python)

Posted by 小明MaxMing on April 14, 2021

题目

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

解题思路

按层进行BFS,如果下一层没有新的节点,返回当前层所有数的和

代码

class Solution:
    def deepestLeavesSum(self, root: TreeNode) -> int:
        q = [root]
        while q:
            tmp = []
            for node in q:
                if node.left:
                    tmp.append(node.left)
                if node.right:
                    tmp.append(node.right)
            if not tmp:
                return sum([n.val for n in q])
            q = tmp

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅