[LeetCode] Second Minimum Node In a Binary Tree

아르당·2026년 2월 13일

LeetCode

목록 보기
147/213
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

모든 노드가 음수가 아닌 값을 가지고 비어 있지 않은 특수한 이진 트리가 주어졌을 때, 각 노드는 정확히 2개 또는 없는 서브노드를 가진다. 만약 두 개의 서브노드를 가진 경우, 해당 노드의 값은 두 서브노드 값 중 더 작은 값이다. 좀 더 정확하게 표현하면, root.val = min(root.left.val, root.right.val)이 항상 성립한다.

주어진 이진 트리에서, 트리의 모든 노드 값으로 이루어진 집합 중에서 두 번째로 작은 값을 출력해야 한다.

만약 두 번째 최소값이 존재하지 않으면 -1을 출력해라.

Example

#1

Input: root = [2, 2, 5, null, null, 5, 7]
Output: 5
Explanation: 가장 작은 값은 2이고, 두 번째 작은 값은 5이다.

#2

Input: root = [2, 2, 2]
Output: -1
Explanation: 가장 작은 값은 2이고, 두 번째로 작은 값은 없다.

Constraints

  • 트리에 있는 노드의 수는 [1, 25] 범위에 있다.
  • 1 <= Node.val <= 2^31 - 1
  • 트리의 각 내부 노드에 대해 root.val == min(root.left.val, root.right.val)

Solved

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int findSecondMinimumValue(TreeNode root) {
        if(root.left == null) return -1;

        Queue<TreeNode> queue = new LinkedList<>();

        queue.add(root);

        int result = Integer.MAX_VALUE;
        int min = root.val;
        boolean flag = false;

        while(!queue.isEmpty()){
            TreeNode node = queue.poll();

            if(node.left != null){
                queue.add(node.left);
                queue.add(node.right);

                if(node.left.val > min){
                    result = Math.min(result, node.left.val);
                    flag = true;
                }

                if(node.right.val > min){
                    result = Math.min(result, node.right.val);
                    flag = true;
                }
            }
        }

        return flag ? result : -1;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글