-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathAbsoluteinimumDifferenceBst.java
More file actions
51 lines (44 loc) · 1.25 KB
/
AbsoluteinimumDifferenceBst.java
File metadata and controls
51 lines (44 loc) · 1.25 KB
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
package tree;
public class AbsoluteinimumDifferenceBst {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
Integer prev;
int minDiff = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
inorder(root);
return minDiff;
}
private void inorder(TreeNode root) {
if (root == null)
return;
inorder(root.left);
if (prev != null)
minDiff = Math.min(minDiff, Math.abs(root.val - prev));
prev = root.val;
inorder(root.right);
}
public static int getMinimumDifferenceWrong(TreeNode root) {
if (root == null) {
return Integer.MAX_VALUE;
} else if (root.left == null && root.right == null) {
return Integer.MAX_VALUE;
} else if (root.left == null) {
int diff = Math.abs(root.val - root.right.val);
return Math.min(diff, getMinimumDifferenceWrong(root.right));
} else if (root.right == null) {
int diff = Math.abs(root.val - root.left.val);
return Math.min(diff, getMinimumDifferenceWrong(root.left));
} else {
int diff = Math.abs(root.val - root.left.val);
int diff2 = Math.abs(root.val - root.right.val);
return Math.min(diff, Math.min(diff2,
Math.min(getMinimumDifferenceWrong(root.left), getMinimumDifferenceWrong(root.right))));
}
}
}