공부/코딩테스트 | 알고리즘

[LeetCode] Maximum Depth of Binary Tree

나는 유찌 2025. 2. 27. 15:00

문제

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.

 

예시

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

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

 


풀기

트리의 최대 깊이를 찾아내는 문제로 나는 DFS를 통해 풀어야겠다고 생각했다.

BFS를 통해서 풀 수도 있다고 함.

 

백준에서 배열에다 값을 넣어 풀어보기만 했지 LeetCode의 주어진 클래스 TreeNode를 어떻게 활용할지 몰라서 이번에도 이런 부분은 GPT 도움을 좀 받았다.

 

LeetCode 문제를 풀어본지 얼마 안된 나 같은 사람들을 위해 아래 코드도 첨부ㅋㅋ...ㅠ..

fun main() {
    val root = TreeNode(3)

    root.left = TreeNode(9)
    root.right = TreeNode(20)

    root.right?.left = TreeNode(15)
    root.right?.right = TreeNode(7)
}

class TreeNode(
    var `val`: Int
) {
    var left: TreeNode? = null
    var right: TreeNode? = null
}

 

예제 1번에 해당하는 값을 넣는 코드이다.


결과

DFS는 재귀를 활용하고 BFS는 큐를 활용한다.

근데 난 DFS로 풀었으니 BFS는 그냥 스킵했다.

 

class Solution {
    fun maxDepth(root: TreeNode?): Int {
        when (root == null) {
            true -> return 0
            false -> return 1 + maxOf(maxDepth(root.left), maxDepth(root.right))
        }
    }
}

 

답은 위와 같다.