본문 바로가기
알고리즘/LeetCode

LeetCode: 104. Maximum Depth of Binary Tree

by 패쓰킴 2025. 8. 27.
728x90

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

 

Maximum Depth of Binary Tree - LeetCode

Can you solve this real interview question? Maximum Depth of Binary Tree - Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf

leetcode.com

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

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


Example 2:
Input: root = [1,null,2]
Output: 2
 

Constraints:
The number of nodes in the tree is in the range [0, 104].
-100 <= Node.val <= 100

 

풀이

왜 이렇게 문제가 달라질때마다 모르겠는건지이....

다른 사람의 BFS 풀이 ->

재귀로도 풀수 있지만 bfs가 더 직관적인듯

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

struct Tests {
    private let solution = Solution()
    
    @Test func test1() async throws {
        #expect(solution.maxDepth(TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))) == 3)
    }
    
    @Test func test2() async throws {
        #expect(solution.maxDepth(TreeNode(1, nil, TreeNode(2))) == 2)
    }
}
728x90

'알고리즘 > LeetCode' 카테고리의 다른 글

LeetCode: 100. Same Tree  (0) 2025.08.22
LeetCode: 1337. The K Weakest Rows in a Matrix  (0) 2025.08.20
LeetCode: 888. Fair Candy Swap  (0) 2025.08.19
LeetCode: 704. Binary Search  (0) 2025.08.17
LeetCode: 441. Arranging Coins  (0) 2025.08.14

댓글