-
Notifications
You must be signed in to change notification settings - Fork 42
/
solution.js
43 lines (35 loc) · 738 Bytes
/
solution.js
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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
function getMin (node) {
while (node.left) {
node = node.left;
}
return node.val;
}
var minDiffInBST = function (root) {
let preVal = getMin(root);
let diff = Infinity;
function inOrder (node) {
if (node === null) {
return;
}
inOrder(node.left);
const val = node.val;
if (val !== preVal && val - preVal < diff) {
diff = val - preVal;
}
preVal = val;
inOrder(node.right);
}
inOrder(root);
return diff;
};