본문 바로가기
Problem Solving/LeetCode

[LeetCode] 783. Minimum Distance Between BST Nodes - Java

by graycode 2026. 10. 14.

• 문제 링크

 

Minimum Distance Between BST Nodes - LeetCode

Can you solve this real interview question? 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.c

leetcode.com

 

• 풀이 코드

public class Solution {

    private int min = Integer.MAX_VALUE, prev = -1;

    public int minDiffInBST(TreeNode root) {
        inorder(root);
        return min;
    }

    private void inorder(TreeNode node) {
        if (node == null) return;
        inorder(node.left);
        if (prev != -1) min = Math.min(min, node.val - prev);
        prev = node.val;
        inorder(node.right);
    }

}

댓글