530. Minimum Absolute Difference in BST, 자바 풀이

이원석·2023년 9월 7일

Leetcode

목록 보기
18/22

[문제]
Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

Example 1:

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

Example 2:


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

https://leetcode.com/problems/minimum-absolute-difference-in-bst/


/**
 * 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 {
    static List<Integer> list;
    public int getMinimumDifference(TreeNode root) {
        list = new ArrayList<>();
        int min_val = Integer.MAX_VALUE;

        dfs(root);
        Collections.sort(list);
        
        for (int i = 0; i < list.size() - 1; i++) {
            int val = Math.abs(list.get(i) - list.get(i + 1));
            min_val = Math.min(min_val, val);
        }

        return min_val;
    }

    static void dfs(TreeNode node) {
        if (node == null) {
            return;
        }

        list.add(node.val);

        dfs(node.left);
        dfs(node.right);
    }
}

// 주어진 BST(이진 탐색 트리)의 노드간의 차의 절대값 중 최소값을 찾아라!
// 각 부모노드의 자식 노드들을 순회하며 list에 추가한다.
// 순회한 노드가 null 인 경우, return 한다.
// 각 노드의 값들을 담은 list를 정렬한 후, 순차적으로 앞뒤 요소들의 차의 절대값을 구하며 최소값을 구하자

0개의 댓글