-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
34 lines (32 loc) · 972 Bytes
/
Copy pathSolution.java
File metadata and controls
34 lines (32 loc) · 972 Bytes
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
class Solution
{
public int minDiffInBST(TreeNode root)
{
return _calculateMin(root, null, null);
}
private int _calculateMin(TreeNode root, Integer lower, Integer upper)
{
if (root == null)
{
return 0;
}
int minimumDifference = Integer.MAX_VALUE;
if (lower != null)
{
minimumDifference = Math.min(root.val - lower, minimumDifference);
}
if (upper != null)
{
minimumDifference = Math.min(upper - root.val, minimumDifference);
}
if (root.left != null)
{
minimumDifference = Math.min(minimumDifference, _calculateMin(root.left, lower, root.val));
}
if (root.right != null)
{
minimumDifference = Math.min(minimumDifference, _calculateMin(root.right, root.val, upper));
}
return minimumDifference == Integer.MAX_VALUE ? 0 : minimumDifference;
}
}