[LeetCode] Minimum Absolute Difference in Bst

아르당·2026년 1월 26일

LeetCode

목록 보기
112/134
post-thumbnail

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

Problem

이진 탐색 트리(BST) root가 주어졌을 때, 트리의 서로 다른 두 노드 값 사이의 최소 절댓값 차이를 반환해라.

Example

#1

Input: root = [4, 2, 6, 1, 3]
Output: 1

#2

Input: root = [1, 0, 48, null, null, 12, 49]
Output: 1

Constraints

  • 트리에 노드 숫자는 [2, 10^4] 범위에 있다.
  • 0 <= Node.val <= 10^5

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 {
    TreeNode pre = null;
    int ans = Integer.MAX_VALUE;

    private void inorder(TreeNode root){
        if(root == null) return;

        inorder(root.left);

        if(pre != null) ans = Math.min(ans, root.val - pre.val);

        pre = root;
        inorder(root.right);

        return;
    }

    public int getMinimumDifference(TreeNode root) {
        inorder(root);

        return ans;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글