Leetcode #404 Sum of Left Leaves

    xiaoxiao2021-03-25  79

    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.

    Explain

    判断是否为左子树并且是否不存在子树,都满足则加上这个val ps:才发现leetcode可以加参数= =

    Code

    # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def sumOfLeftLeaves(self, root, isleft=False): """ :type root: TreeNode :rtype: int """ if not root: return 0 if not root.left and not root.right: return root.val if isleft else 0 return self.sumOfLeftLeaves(root.left, True) + self.sumOfLeftLeaves(root.right, False)
    转载请注明原文地址: https://ju.6miu.com/read-17655.html

    最新回复(0)