-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy pathinorder-successor-in-bst.js
60 lines (51 loc) · 1.04 KB
/
inorder-successor-in-bst.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
/**
* Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
*
* Note: If the given node has no in-order successor in the tree, return null.
*/
/**
* Recursion
*
* @param {TreeNode} root
* @param {TreeNode} p
* @return {TreeNode}
*/
const inorderSuccessorR = (root, p) => {
if (!root) {
return null;
}
if (root.val <= p.val) {
return inorderSuccessorR(root.right, p);
}
const successor = inorderSuccessorR(root.left, p);
return successor ? successor : root;
};
/**
* Iterative
*
* @param {TreeNode} root
* @param {TreeNode} p
* @return {TreeNode}
*/
const inorderSuccessor = (root, p) => {
if (p.right) {
return getMinNode(p.right);
}
let successor = null;
while (root) {
if (p.val >= root.val) {
root = root.right;
} else {
successor = root;
root = root.left;
}
}
return successor;
};
const getMinNode = root => {
while (root.left) {
root = root.left;
}
return root;
};
export { inorderSuccessor, inorderSuccessorR };