题目描述
将所有的左叶子节点相加,返回其加和。
代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
self.ans = 0
self.helper(root, False)
return self.ans
def helper(self, root, is_left):
if not root:
return None
if is_left and not root.left and not root.right:
self.ans += root.val
self.helper(root.left, True)
self.helper(root.right, False)