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

 

Maximum Depth of Binary Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

- 큐를 사용한 BFS로 구현

- 최초 Node가 nil인 경우 처리

- 한번 반복 될때마다 깊이를 +1 카운트

- 현재 큐의 길이(같은 레벨에 위치한 노드의 전체 개수)만큼 다시 추가해주는 작업

class Solution {
    func maxDepth(_ root: TreeNode?) -> Int {
        guard let root = root else {
            return 0
        }
        var queue = [root]
        var answer = 0
        while !queue.isEmpty {
            answer += 1
            (0..<queue.count).forEach { _ in
                let current = queue.removeFirst()
                if let left = current.left {
                    queue.append(left)    
                }
                if let right = current.right {
                    queue.append(right)        
                }
            }
        }
        return answer
    }
}