-
Notifications
You must be signed in to change notification settings - Fork 0
/
findSecondMinimumValue.js
58 lines (47 loc) · 1.11 KB
/
findSecondMinimumValue.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var findSecondMinimumValue = function(root) {
if (root === null) return -1
let res = []
function inOrder(root) {
if (root) {
res.push(root.val)
inOrder(root.left)
inOrder(root.right)
}
}
inOrder(root)
res = [...new Set(res)].sort((pre, next) => pre - next)
return res.length > 1 ? res[1] : -1
};
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var findSecondMinimumValue = function(root) {
function helper(root, min) {
if (root === null) return -1
if (root.val > min) return root.val
let l = helper(root.left, min)
let r = helper(root.right, min)
if (l > min && r > min) return Math.min(l, r)
return Math.max(l, r)
}
return helper(root, root.val)
};