https://leetcode.com/problems/minimum-absolute-difference-in-bst/?tab=Description
找出BST中两个相邻值得最小gap
记录pre(Integer),中序遍历
public class Solution {
Integer min = Integer.MAX_VALUE;
Integer pre = null;
public int getMinimumDifference(TreeNode root) {
if (root == null) {
return min;
}
getMinimumDifference(root.left);
if (pre != null) {
min = Math.min(min, root.val - pre);
}
pre = root.val;
getMinimumDifference(root.right);
return min;
}
}
如果是一个普通的树呢?
先序遍历!!递归之前要保证当前节点已经加入到set之中
public class Solution {
TreeSet<Integer> set = new TreeSet();
int min = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
if (root == null) {
return min;
}
if (!set.isEmpty()) {
if (set.floor(root.val) != null) {
min = Math.min(min, root.val - set.floor(root.val));
}
if (set.ceiling(root.val) != null) {
min = Math.min(min, set.ceiling(root.val) - root.val);
}
}
set.add(root.val);
getMinimumDifference(root.left);
getMinimumDifference(root.right);
return min;
}
}