LeetCode 404 Sum of Left Leaves (Python)

Posted by 小明MaxMing on August 24, 2020

题目

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

解题思路

递归,递归的时候传一个标记,是左子树还是右子树

代码

class Solution:
    def sumOfLeftLeaves(self, root: TreeNode) -> int:
        def sumOfLeft(root, flag):
            if not root:
                return 0
            if flag and not root.left and not root.right:
                return root.val
            return sumOfLeft(root.left, True) + sumOfLeft(root.right, False)
        
        return sumOfLeft(root, False)

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅