itisjustK
코딩과 사람 사는 이야기
itisjustK
전체 방문자
오늘
어제
  • 분류 전체보기 (207)
    • 일이삼사오육칠팔구십일이삼사오육칠팔구십일이삼사오육칠.. (0)
    • Web (43)
      • html & css (9)
      • django & python (15)
      • java script (9)
    • iOS (51)
      • Swift (42)
      • SwiftUI (5)
    • CS (25)
      • 자료구조 (6)
      • 운영체제 (3)
      • 데이터베이스 (9)
      • 네트워크 (7)
    • PS (34)
      • 알고리즘 & 자료구조 (0)
    • Life (36)
    • Retrospective (15)
    • Book (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • CS
  • 연결리스트
  • SWIFT
  • AppleDevloperAcademy
  • 생활코딩 #이고잉 #HTML #코딩 #개발자
  • crud
  • 생활코딩
  • 킨디
  • nosql
  • POSTECH
  • mongodb
  • 개발자
  • 독립서점
  • 세그멘테이션
  • CoreData
  • SwiftUI
  • 어플
  • 점주
  • ios
  • binding

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
itisjustK

코딩과 사람 사는 이야기

[Leetcode - Swift] 111. Minimum Depth of Binary Tree
PS

[Leetcode - Swift] 111. Minimum Depth of Binary Tree

2023. 2. 1. 15:10

문제

https://leetcode.com/problems/minimum-depth-of-binary-tree/description/

 

Minimum Depth of Binary Tree - LeetCode

Minimum Depth of Binary Tree - Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children.   Example 1: [https://

leetcode.com

 

풀이

 1. 재귀

 2 .BFS

 

 최소 깊이를 찾는다는 것은 자식 노드가 아무 것도 없는 노드를 빨리 발견하는 것이다.

 그래서 BFS로 순회하면서 자식 노드가 없는 노드를 발견하면 그때의 깊이를 반환하려는 풀이 방법을 생각했다.

 하지만, BFS를 Queue로 구현하면서 깊이를 어떻게 계산해주어야 할지 생각이 안났다.

 

 그래서, 104번 문제와 비슷하게 재귀를 이용하여 풀었다.

 본 함수를 재귀적으로 호출하면서 왼쪽 값, 오른쪽 값의 최소값을 반환하도록 했다.

 최소 깊이를 찾는 즉시 순회를 종료하는 BFS와 달리, 모든 노드를 순회하기 때문에 시간복잡도가 조금 더 걸린다.

 하지만 worst case는 O(n)으로 같다.

 

코드

// 1. 재귀

class Solution {
    func minDepth(_ root: TreeNode?) -> Int {
        guard let root = root else { return 0 }
        
        let left = minDepth(root.left)
        let right = minDepth(root.right)
        
        if left == 0 {
            return right + 1
        } else if right == 0 {
            return left + 1
        } else {
            return min(left, right) + 1
        }
    }
}

 

// 2. BFS

class Solution {
    func minDepth(_ root: TreeNode?) -> Int {
        guard let root = root else { return 0 }
        
        var queue: [TreeNode?] = [root]
        var depth = 1
        
        while !queue.isEmpty {
            depth += 1
            for _ in 0..<queue.count {
                let current = queue.removeFirst()
                
                if let left = current?.left {
                    queue.append(left)
                }
                if let right = current?.right {
                    queue.append(right)
                }
                
                if current?.left == nil && current?.right == nil {
                    return depth
                }
            }
        }
        
        return depth
    }
}
저작자표시 (새창열림)

'PS' 카테고리의 다른 글

[Leetcode - Swift] 1091 Shortest Path in Binary Matrix  (0) 2023.02.18
[프로그래머스 - Swift] 오픈 채팅방 (2019 KAKAO BLIND RECRUITMENT)  (0) 2023.02.15
[Leetcode - Swift] 94. Binary Tree Inorder Traversal  (0) 2023.02.01
[백준 - Swift] 19583 사이버 개강총회  (0) 2023.01.24
[백준 - Swift] 4358 생태학  (0) 2023.01.20
    'PS' 카테고리의 다른 글
    • [Leetcode - Swift] 1091 Shortest Path in Binary Matrix
    • [프로그래머스 - Swift] 오픈 채팅방 (2019 KAKAO BLIND RECRUITMENT)
    • [Leetcode - Swift] 94. Binary Tree Inorder Traversal
    • [백준 - Swift] 19583 사이버 개강총회
    itisjustK
    itisjustK

    티스토리툴바