Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Solution1 for BST:中序遍历
思路:
Time Complexity: O(N) Space Complexity: O(N) 递归缓存
Solution2 for BT:遍历 + TreeSet
思路:
Time complexity O(NlgN), Space complexity O(N)
Solution1-BST Code:
public 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;
}
}
Solution2-BT Code:
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;
}
}