404 左叶子之和
给定二叉树的根节点 root
,返回所有左叶子之和。
输入: root = [3,9,20,null,null,15,7]
输出: 24
解释: 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
输入: root = [1]
输出: 0
# 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:
# 非递归
# if not root: return 0
# if not root.left and not root.right:return 0
# st = []
# st.append(root)
# res = 0
# while st:
# cur = st.pop()
# if cur.left and not cur.left.left and not cur.left.right:
# res += cur.left.val
# if cur.left:
# st.append(cur.left)
# if cur.right:
# st.append(cur.right)
# return res
# 递归
if not root: return 0
left_left_sum = self.sumOfLeftLeaves(root.left)
right_left_sum = self.sumOfLeftLeaves(root.right)
cur_val_sum = 0
if root.left and not root.left.left and not root.left.right:
cur_val_sum = root.left.val
return left_left_sum + right_left_sum + cur_val_sum