forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
_530.java
55 lines (45 loc) · 1.3 KB
/
_530.java
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
49
50
51
52
53
54
55
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.Iterator;
import java.util.TreeSet;
/**
* Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
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.
*/
public class _530 {
public int getMinimumDifference(TreeNode root) {
TreeSet<Integer> treeset = new TreeSet<>();
treeset.add(root.val);
dfs(root, treeset);
int diff = Integer.MAX_VALUE;
Iterator<Integer> iterator = treeset.iterator();
int prev = iterator.next();
while (iterator.hasNext()) {
int current = iterator.next();
diff = Math.min(diff, Math.abs(current - prev));
prev = current;
}
return diff;
}
private void dfs(TreeNode root, TreeSet<Integer> treeset) {
if (root.left != null) {
treeset.add(root.left.val);
dfs(root.left, treeset);
}
if (root.right != null) {
treeset.add(root.right.val);
dfs(root.right, treeset);
}
}
}