[LeetCode] 404. Sum of Left Leaves (Daily Question)
문제
Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children.A left leaf is a leaf that is the left child of another node.
이진트리가 주어졌을 때, 왼쪽 leaf node의 값의 합을 구하는 문제이다.
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: 24 Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.
Example 2: Input: root = [1] Output: 0
풀이
아이디어
재귀함수로 트리를 순회하며 왼쪽 leaf node인지 확인하고, 그렇다면 값을 더해준다.
코드
# 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], isLeft: bool=False) -> int:
sm = 0
# left leaf node이면 값을 더해줌
if isLeft and root.left is None and root.right is None:
sm += root.val
else:
# 좌측 자식 노드 탐색
if root.left is not None:
sm += self.sumOfLeftLeaves(root.left, True)
# 우측 자식 노드 탐색
if root.right is not None:
sm += self.sumOfLeftLeaves(root.right, False)
return sm
후기
난이도
객체형식으로 주어져서 리스트의 몇 번째 노드가 자식노드인지 판단하는 과정이 필요없어 쉽게 풀 수 있었다.