SeangG
def _(): _()
SeangG
전체 방문자
오늘
어제
  • 분류 전체보기 (37)
    • Programming Language (0)
      • Python (0)
      • Web (0)
    • Algorithm (34)
    • Art (0)
      • 3D Modeling (0)
      • Pixel (0)
      • Picture (0)
    • Game (0)
    • Project (3)
      • Problems (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 문자열
  • Fast Refresh
  • 로마 숫자
  • Daily Question
  • react.js
  • dfs
  • leetcode
  • Queue
  • string
  • Leecode
  • github oauth
  • spring boot
  • graph
  • 매핑 테이블
  • Python
  • Tree
  • LeedCode
  • WSL
  • next.js
  • BFS

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
SeangG

def _(): _()

[LeetCode] 404. Sum of Left Leaves (Daily Question)
Algorithm

[LeetCode] 404. Sum of Left Leaves (Daily Question)

2024. 4. 15. 09:48

문제


 

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

 

후기


난이도

객체형식으로 주어져서 리스트의 몇 번째 노드가 자식노드인지 판단하는 과정이 필요없어 쉽게 풀 수 있었다.

재귀함수를 잘 다룬다면 어렵지 않게 풀 수 있을 것이다.

 

'Algorithm' 카테고리의 다른 글

[LeetCode] 623. Add One Row to Tree (Daily Question)  (0) 2024.04.16
[LeetCode] 129. Sum Root to Leaf Numbers (Daily Question)  (0) 2024.04.15
[LeetCode] 85. Maximal Rectangle (Daily Question)  (0) 2024.04.13
[LeetCode] 42. Trapping Rain Water (Daily Question)  (0) 2024.04.12
[LeetCode] 402. Remove K Digits (Daily Question)  (0) 2024.04.11
    'Algorithm' 카테고리의 다른 글
    • [LeetCode] 623. Add One Row to Tree (Daily Question)
    • [LeetCode] 129. Sum Root to Leaf Numbers (Daily Question)
    • [LeetCode] 85. Maximal Rectangle (Daily Question)
    • [LeetCode] 42. Trapping Rain Water (Daily Question)
    SeangG
    SeangG

    티스토리툴바