首页 > 其他分享 >404. Sum of Left Leaves

404. Sum of Left Leaves

时间:2022-12-27 17:45:43浏览次数:52  
标签:right val res Sum self 404 root Leaves left

Given the root of a binary tree, return the sum of all left leaves.

A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

Example 1:
avatar

Input: root = [3,9,20,null,null,15,7]
Output: 24
Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.
Example 2:

Input: root = [1]
Output: 0

Constraints:

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

# 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 sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        res = 0
        def preorder(root):
            nonlocal res
            if root is None:
                return
            if root.left and (not root.left.left and not root.left.right):
                res += root.left.val
            preorder(root.left)
            preorder(root.right)
        preorder(root)
        return res

标签:right,val,res,Sum,self,404,root,Leaves,left
From: https://www.cnblogs.com/bernieloveslife/p/17008612.html

相关文章

  • Atcoder Beginner Contest ABC 283 Ex Popcount Sum 题解 (类欧几里得算法)
    题目链接令\(p=\lfloor\frac{n-r}m\rfloor\),则我们其实是要对所有\(0\lei\le29\)求\(\sum_{j=0}^p(\lfloor\frac{mj+r}{2^i}\rfloormod\2)\)。右边那个东西如果没......
  • 泪流满面的404页面
    <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""​​http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd​​​"><htmlxmlns="​​​http://ww......
  • Pytest插件pytest-assume多重断言
    Pytest插件pytest-assume多重断言背景importpytestdeftest_assume1():assert1==2print('hello')assert2==3if__name__=='__main__':......
  • Data & Cloud Summit 2021 活动小记
    前言        大家好,我是梦想家。前段时间我写了一篇文章,​​《参加七牛云“PISA”发布会随想录》​​,当时在评论区说到,如果点赞过15,7月30日将在上海浦东香格里拉......
  • AT_jag2018summer_day2_a 10^N+7 题解
    题目传送门题目大意有三个非负整数$x,y,z$,找到符合以下条件的最小非负整数\(n\);$n\{\rm\mod}\10^1+7\=\x$$n\{\rm\mod}\10^2+7\=\y$$n\{\rm\mo......
  • [LeetCode] 2389. Longest Subsequence With Limited Sum
    Youaregivenanintegerarray nums oflength n,andanintegerarray queries oflength m.Return anarray answer oflength m where answer[i] ist......
  • 解决“ ignoring dependency for device, assuming no driver”错误
    最近升级内核版本,需要把内核从4.14升级到4.19,控制台就是没有打印,通过strings__log_buf发现报错dw-apb-uartf8041000.serial1:ignoringdependencyfordevice,assum......
  • P2404 自然数的拆分问题
    #include<iostream>#include<algorithm>usingnamespacestd;constintN=10;intn;intpath[N];voiddfs(intsum,intstart,intk){if(sum==n)......
  • sumBy 数字运算符
    _=require('lodash');//varasync=require('async');//varasyncSave=require('asyncSave');varobjects=[{'n':4},{'n':2},{'n':8},{'n':6}]......
  • C++实现checksum校验和计算
    校验和概念差错控制编码是为了检查传输中的错误下面将一个报文的数据部分称为d,报文的冗余部分称为r发送方根据约定好的差错控制编码关系(关系指出dr之间的关系)和d生成出......