首页 > 其他 > 详细

LeetCode 404.左叶子之和

时间:2020-12-06 22:32:49      阅读:37      评论:0      收藏:0      [点我收藏+]

404. 左叶子之和

Difficulty: 简单

计算给定二叉树的所有左叶子之和。

示例:

    3
   /   9  20
    /     15   7

在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24

Solution

Language: ****

错误解法:用层序遍历上瘾了。。。。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
?
class Solution:
    def sumOfLeftLeaves(self, root: TreeNode) -> int:
        if not root:
            return 0
        queue, res, tmp = [root], 0, root.val
        while queue:
            size = len(queue)
            for i in range(size):
                node = queue.pop(0)
                if i == 0:
                    res += node.val
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return res-tmp

LeetCode 404.左叶子之和

原文:https://www.cnblogs.com/swordspoet/p/14094241.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!