IT/Computer Science
[Leetcode/Tree] 404. Sum of Left Leaves
Diana Kang
2025. 3. 12. 21:58
# 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
total = 0
# 왼쪽 자식이 리프 노드라면 값 추가
if root.left and not root.left.left and not root.left.right:
total += root.left.val
# 왼쪽과 오른쪽 서브트리 탐색 (재귀 호출)
total += self.sumOfLeftLeaves(root.left)
total += self.sumOfLeftLeaves(root.right)
return total