530. Minimum Absolute Difference in BST
2026/1/12小于 1 分钟约 296 字
530. Minimum Absolute Difference in BST
难度: Easy
题目描述
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
Constraints:
- The number of nodes in the tree is in the range
[2, 104]. 0 <= Node.val <= 105
Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/
解题思路
代码实现
解决方案
java
/**
* 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 {
int min = Integer.MAX_VALUE;
TreeNode pre;
public int getMinimumDifference(TreeNode root) {
dfs(root);
return min;
}
public void dfs(TreeNode root) {
if (root == null) {
return;
}
if (pre == null) {
pre = root;
}
TreeNode left = root.left;
TreeNode right = root.right;
dfs(left);
if (pre != null && pre != root) {
min = Math.min(min, Math.abs(pre.val - root.val));
pre = root;
}
dfs(right);
}
}