404. Sum of Left Leaves (Easy)

Posted Yancea --- TO BE A DOER !

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了404. Sum of Left Leaves (Easy)相关的知识,希望对你有一定的参考价值。

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.

题意:计算所有左叶子的和
思路:遍历二叉树 

1.检查当前节点的左子节点是否是左子叶;
2.若是叶子节点,则返回左子叶的值加上对当前结点的右子节点调用递归的结果;
3.若不是叶子结点,我们对左右子节点分别调用递归函数,返回二者之和;

# 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):
        """
        :type root: TreeNode
        :rtype: int
        """
        ans = 0
        l, r = root.left, root.right
        if root:
            if l and (l.left or l.right) is None:
                ans += l.val
            ans += self.sumOfLeftLeaves(l) + self.sumOfLeftLeaves(r)
        return ans

 

以上是关于404. Sum of Left Leaves (Easy)的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 404. Sum of Left Leaves

404. Sum of Left Leaves

404. Sum of Left Leaves

404. Sum of Left Leaves

404. Sum of Left Leaves

LeetCode 404. Sum of Left Leaves