111. Minimum Depth of Binary Tree

양성준·2025년 5월 19일

코딩테스트

목록 보기
56/102

문제

풀이

class Solution {
    int answer = Integer.MAX_VALUE;
    public int minDepth(TreeNode root) {
        if(root == null) { // [] 빈 배열이 들어오는 경우
            return 0;
        }

        DFS(root, 1);
        return answer;
    }

    public void DFS(TreeNode root, int depth) {
        if(root == null) {
            return;
        }

        if(root.left == null && root.right == null) { // 리프 노드에 도착했을 때만 최소 depth 계산 
            answer = Math.min(answer, depth);
        }

        DFS(root.left, depth+1);
        DFS(root.right, depth+1);
    }
}
  • 리프 노드일 때만 깊이를 계산하여 최소 깊이 탐색
profile
백엔드 개발자

0개의 댓글