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 416. Partition Equal Subset Sum
给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
107 0
LeetCode 416. Partition Equal Subset Sum
|
人工智能 索引
LeetCode 1013. 将数组分成和相等的三个部分 Partition Array Into Three Parts With Equal Sum
LeetCode 1013. 将数组分成和相等的三个部分 Partition Array Into Three Parts With Equal Sum
Leetcode-Medium 416. Partition Equal Subset Sum
Leetcode-Medium 416. Partition Equal Subset Sum
120 0
LeetCode之Sum of Left Leaves
LeetCode之Sum of Left Leaves
95 0
|
移动开发
[LeetCode] Two Sum II - Input array is sorted
Problem Description: Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
1008 0