530. Minimum Absolute Difference in BST
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Solution 1://先遍历左节点然后把左节点设为prev ,然后算差值,把自己设为prev然后遍历右节点,保证root永远大于prev
class Solution {
int min = Integer.MAX_VALUE;
Integer prev = null;
public int getMinimumDifference(TreeNode root) {
if (root == null)
return min;
getMinimumDifference(root.left);
if (prev != null)
min = Math.min(min, root.val - prev);
prev = root.val;
getMinimumDifference(root.right);
return min;
}
}
Solution 2://用先序遍历的方法
class Solution {
int min = Integer.MAX_VALUE;
TreeSet<Integer> set = new TreeSet<>();
public int getMinimumDifference(TreeNode root) {
if (root == null)
return min;
if (!set.isEmpty()) {
if (set.floor(root.val) != null) //set.floor(val)找到set中等于val或小于val的最大的数
min = Math.min(min, root.val - set.floor(root.val));
if (set.ceiling(root.val) != null) //set.ceiling(val)找到set中等于val或大于val的最小的数
min = Math.min(min, set.ceiling(root.val) - root.val);
}
set.add(root.val);
getMinimumDifference(root.left);
getMinimumDifference(root.right);
return min;
}
}
浙公网安备 33010602011771号