문제 설명

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

Input: root = [3,9,20,null,null,15,7]
Output: 2

Example 2:

Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5

Constraints:

  • The number of nodes in the tree is in the range [0, 10^5].
  • -1000 <= Node.val <= 1000

문제풀이

BFS를 이용해서 해결, DFS를 이용하면 Depth 처리가 좀더 쉬웠을듯 한데 BFS 경우 한 Depth 를 한 루트에서 모두 처리해 주어 Depth 처리를 해주었다.

class Solution {
    func minDepth(_ root: TreeNode?) -> Int {
        guard let root = root else { return 0 }
        var queue: [TreeNode] = [root]
        var minDepth = 0
        
        while !queue.isEmpty {
            minDepth += 1
            
            for _ in 0..<queue.count {
                let node = queue.removeFirst()
                if node.left == nil && node.right == nil { return minDepth }
                if let leftNode = node.left { queue.append(leftNode) }
                if let rightNode = node.right { queue.append(rightNode) }
            }
        }
        return minDepth
    }
}

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