forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution3.java
40 lines (28 loc) · 896 Bytes
/
Solution3.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
/// Source : https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/
/// Author : liuyubobobo
/// Time : 2018-04-30
import java.util.ArrayList;
import java.util.Collections;
/// Using inorder to traverse all nodes
/// and calculates the result during the inorder traverse
///
/// Time Complexity: O(n)
/// Space Complexity: O(logn)
class Solution3 {
private Integer prev = null;
public int getMinimumDifference(TreeNode root) {
prev = null;
return inOrder(root);
}
private int inOrder(TreeNode node){
if(node == null)
return Integer.MAX_VALUE;
int res = Integer.MAX_VALUE;
res = Math.min(res, inOrder(node.left));
if(prev != null)
res = Math.min(res, node.val - prev);
prev = node.val;
res = Math.min(res, inOrder(node.right));
return res;
}
}