-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproblem_036.js
85 lines (76 loc) Β· 1.37 KB
/
problem_036.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
/**
* Returns the largest node in binary search tree
* @param {TreeNode} root
* @return {TreeNode}
*/
function findLargestNode(root) {
let curr = root;
while(curr !== null) {
curr = curr.right;
}
return curr;
}
/**
* Returns the predecessor of node in binary search tree
* @param {TreeNode} root
* @param {TreeNode} maxNode
* @return {TreeNode}
*/
function findSecondLargest(root, maxNode) {
// Check if maxNode has a left child
// If it exists, it's the second largest
// (see Scenario #2 below)
if (maxNode.left !== null) {
let curr = maxNode.left;
while (curr.right !== null) {
curr = curr.right;
}
return curr;
}
// Check right subtree if max is last on right
let lastRight = null;
let curr = root;
while (curr.val !== maxNode.val) {
if (curr.val < maxNode.val) {
lastRight = curr;
curr = curr.right;
} else {
curr = curr.left;
}
}
return lastRight;
}
}
/*
* SCENARIO #1:
* 10
* /
* 5
* \
* 8
*/
/*
* SCENARIO #2:
* 10
* / \
* 5 20
* \
* 30
* /
* 25
*/
/*
* SCENARIO #3:
* 10
* / \
* 5 20
* \
* 30
*/