-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathProblem36.js
66 lines (61 loc) · 1.42 KB
/
Problem36.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
59
60
61
62
63
64
65
66
// Problem 36
//
// This problem was asked by Dropbox.
//
// Given the root to a binary search tree, find the second largest node in the tree.
//
// O(N) Time complexity
// O(1) Space complexity
// N is the number of nodes in binary search tree
// get predecessor of max
/**
* Returns the second largest node in binary search tree
* @param {TreeNode} root
* @return {TreeNode}
*/
function secondLargest(root) {
if (root === null) return null;
const max = getMax(root);
return predecessor(root, max);
}
/**
* Returns the largest node in binary search tree
* @param {TreeNode} root
* @return {TreeNode}
*/
function getMax(root) {
let curr = root;
while (curr.right !== null) {
curr = curr.right;
}
return curr;
}
/**
* Returns the predecessor of node in binary search tree
* @param {TreeNode} root
* @param {TreeNode} node
* @return {TreeNode}
*/
function predecessor(root, node) {
if (node.left !== null) {
let curr = node.left;
while (curr.right !== null) {
curr = curr.right;
}
return curr;
}
// get the last right traversing through root to find node
// last right would be null, if we are trying to find the predecessor of min node
let lastRight = null;
let curr = root;
while (curr.val !== node.val) {
if (curr.val < node.val) {
lastRight = curr;
curr = curr.right;
} else {
curr = curr.left;
}
}
return lastRight;
}
export default secondLargest;