LeetCode 404. Sum of Left Leaves

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

v2-245d8686f680b89b1be5e30d928af9e2_1440w.jpg

Description



Find the sum of all left leaves in a given binary tree.


Example:


3
   / \
  9  20
    /  \
   15   7


There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.


描述



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


示例:


3
   / \
  9  20
    /  \
   15   7


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


思路


  • 使用任意一种方式遍历二叉树,找到左叶子结点的时候,将其值进行加和即可。
  • 判断是否为左叶子节点的方法是:判断节点有左节点,并且左节点的左右节点为空;


# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-09-14 08:23:43
# @Last Modified by:   何睿
# @Last Modified time: 2019-09-14 08:33:06
# 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:
        self.res = 0
        self.__traversal(root)
        return self.res
    def __traversal(self, root):
        if not root:
            return
        if root.left and not root.left.left and not root.left.right:
            self.res += root.left.val
        self.__traversal(root.left)
        self.__traversal(root.right)

源代码文件在 这里


目录
相关文章
[LeetCode]--404. Sum of Left Leaves
Find the sum of all left leaves in a given binary tree. Example: 3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respective
947 0
|
2月前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
2月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
2月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3
|
2月前
|
容器
《LeetCode》——LeetCode刷题日记1
《LeetCode》——LeetCode刷题日记1
|
2月前
|
算法
LeetCode刷题---21.合并两个有序链表(双指针)
LeetCode刷题---21.合并两个有序链表(双指针)
|
2月前
|
算法 测试技术
LeetCode刷题--- 430. 扁平化多级双向链表(深度优先搜索)
LeetCode刷题--- 430. 扁平化多级双向链表(深度优先搜索)
|
2月前
|
存储
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
144 38
|
10天前
刷题之Leetcode160题(超级详细)
刷题之Leetcode160题(超级详细)
11 0

热门文章

最新文章