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 respectively. Return 24.
# 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
        """
        if root is None:
            return 0
        res = 0
        def preorder(root):
            nonlocal res
            if root.left:
                if root.left.left is None and root.left.right is None:
                    res += root.left.val
            if root.left:
                preorder(root.left)
            if root.right:
                preorder(root.right)
        preorder(root)
        return res
原文地址:https://www.cnblogs.com/bernieloveslife/p/10234249.html