日野弥生:勉強しよう
LeetCode 404 - 左叶子之和
发表于2025年03月09日
递归解题,整体思路是先根遍历。注意即使是收集左叶子的和,也一定是要遍历右子树。所以仅在对根节点的处理进行求和运算即可,正常进行先根遍历。
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
result = 0
def sumOfLeftLeavesIMPL(root: Optional[TreeNode]):
nonlocal result
if not root:
return
if root.left and not root.left.left and not root.left.right:
result += root.left.val
sumOfLeftLeavesIMPL(root.left)
sumOfLeftLeavesIMPL(root.right)
sumOfLeftLeavesIMPL(root)
return result