Step-by-Step

[Java] Daily LeetCode Challenge 783. Minimum Distance Between BST Nodes 본문

언어/JAVA

[Java] Daily LeetCode Challenge 783. Minimum Distance Between BST Nodes

희주(KHJ) 2023. 2. 17. 12:39

https://leetcode.com/problems/minimum-distance-between-bst-nodes/

 

Minimum Distance Between BST Nodes - LeetCode

Minimum Distance Between BST Nodes - Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.   Example 1: [https://assets.leetcode.com/uploads/2021/02/05/bst1.jpg] Input: root

leetcode.com

 

Tree를 DFS로 돌면서 val 값을 모두 PQ에 넣어준 후,

하나씩 꺼내면서 이전 val과의 차이를 구하면서 최솟값을 알아내면 된다

 

릿코드는 에러 발생한 테스트케이스 알려줘서 너무 좋은 듯..!

 

 

[코드]

import java.util.*;
class Solution {
    public PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Collections.reverseOrder());
    public int minDiffInBST(TreeNode root) {
        getMin(root);

        int minVal = Integer.MAX_VALUE, last = pq.poll();
        while(!pq.isEmpty()){
            int now = pq.poll();
            minVal = Math.min(minVal, last-now);
            last = now;
        }

        return minVal;
    }

    public void getMin(TreeNode node){
        pq.add(node.val);

        if(node.left != null)
            getMin(node.left);
        
        if(node.right != null)
            getMin(node.right);
        
    }
}

 

Comments