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:39https://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);
}
}
'언어 > JAVA' 카테고리의 다른 글
[Java] Daily LeetCode Challenge 226. Invert Binary Tree (0) | 2023.02.18 |
---|---|
[Java] LeetCode 395. Longest Substring with At Least K Repeating Characters (0) | 2023.02.17 |
[Java] Daily LeetCode Challenge 67. Add Binary (0) | 2023.02.14 |
[Java] Daily LeetCode Challenge 2306. Naming a Company (0) | 2023.02.09 |
[Java] Daily LeetCode Challenge 904. Fruit Into Baskets (0) | 2023.02.07 |
Comments