Star

Leetcode 530. Minimum Absolute Difference in BST

Question

Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

Example:

1
2
3
4
5
6
7
8
9
10
Input:
1
\
3
/
2
Output:
1

Explanation: The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3). Note: There are at least two nodes in this BST

Explanation

按照之前Leetcode 94.Binary Tree Inorder Traversal的思路,可用递归来做。但是如果不是BST的话,我们也可以用Treeset来存值,同样用递归。 两种方法如下,第一种Time complexity O(N), space complexity O(1),第二种的话Time complexity O(NlgN), space complexity O(N).

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
// Recursive:
Time complexity O(N), space complexity O(1).
int min = Integer.MAX_VALUE;
TreeNode pre = null;
public int getMinimumDifference(TreeNode root) {
if (root == null) return 0;
getMinimumDifference(root.left);
if (pre != null) {
min = Math.min(min, root.val - pre.val);
}
pre = root;
getMinimumDifference(root.right);
return min;
}
// Another Recursive
// If the tree is not BST, we can just use TreeSet to store all the nodes
TreeSet<Integer> set = new TreeSet<>();
int min = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
if (root == null) return 0;
if (!set.isEmpty()) {
if (set.ceiling(root.val)!=null) {
min = Math.min(min, Math.abs(root.val - set.ceiling(root.val)));
}
if (set.floor(root.val)!=null) {
min = Math.min(min, Math.abs(root.val - set.floor(root.val)));
}
}
set.add(root.val);
getMinimumDifference(root.left);
getMinimumDifference(root.right);
return min;
}
}