-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
47 lines (39 loc) · 1.04 KB
/
Solution.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
import java.util.Arrays;
/**
* User: Changle
* Date: 2018-02-14 16:10
* Source: https://leetcode.com/problems/minimum-distance-between-bst-nodes/
*/
/*
取出 BST 中的每个元素放到数组中排序,
再求相邻元素之间差值的最小值
*/
public class Solution {
private int[] nodeArr;
private int size;
private int index;
public int minDiffInBST(TreeNode root) {
int result = Integer.MAX_VALUE;
nodeArr = new int[size(root)];
fillArray(root);
Arrays.sort(nodeArr);
for(int i = 1;i < nodeArr.length;i++){
result = Math.min(nodeArr[i] - nodeArr[i - 1],result);
}
return result;
}
private int size(TreeNode root){
if(root == null){
return 0;
}
return size(root.left) + size(root.right) + 1;
}
private void fillArray(TreeNode root){
if(root == null){
return;
}
nodeArr[index++] = root.val;
fillArray(root.left);
fillArray(root.right);
}
}