-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathMinimumAbsoluteDifferenceInBST.js
More file actions
69 lines (61 loc) · 1.38 KB
/
MinimumAbsoluteDifferenceInBST.js
File metadata and controls
69 lines (61 loc) · 1.38 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Source : https://leetcode.com/problems/minimum-absolute-difference-in-bst
// Author : Dean Shi
// Date : 2017-03-11
/***************************************************************************************
*
* Given a binary search tree with non-negative values, find the minimum absolute
* difference between values of any two nodes.
*
* Example:
*
* Input:
*
* 1
* \
* 3
* /
* 2
*
* Output:
* 1
*
* Explanation:
* The minimum absolute difference is 1, which is the difference between 2 and 1 (or
* between 2 and 3).
*
* Note:
* There are at least two nodes in this BST.
*
*
***************************************************************************************/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var getMinimumDifference = function(root) {
const hash = []
let result = Number.MAX_SAFE_INTEGER
helper(root, hash)
hash.sort((a,b) => a - b)
let curr, diff, prev = hash[0]
for (let i = 1; i < hash.length; i++) {
curr = hash[i]
diff = curr - prev
if (diff < result) result = diff
prev = curr
}
return result
};
function helper(root, hash) {
if (!root) return
hash.push(root.val)
helper(root.left, hash)
helper(root.right, hash)
}