forked from yangshun/lago
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearchTree.js
85 lines (71 loc) · 1.93 KB
/
BinarySearchTree.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
import BinaryTreeNode from './BinaryTreeNode';
import BinaryTree from './BinaryTree';
class BinarySearchTree extends BinaryTree {
/**
* Recursively insert a new value in the BST.
* @param {*} value The value being inserted
* @param {BinaryTreeNode} node The current node. Param is not required.
* @return {undefined}
*/
insert(value, node) {
if (!this.root) {
this.root = new BinaryTreeNode(value);
}
node = node || this.root;
const nodeValue = node.value;
if (value < nodeValue) {
const { left } = node;
if (!left) {
node.left = new BinaryTreeNode(value);
return;
}
this.insert(value, left);
return;
}
const { right } = node;
if (!right) {
node.right = new BinaryTreeNode(value);
return;
}
this.insert(value, right);
}
/**
* Recursively search for a value in the BST
* @param {*} value The value to search for.
* @param {*} node The current node.
* @return {Boolean} True if value is found, false if not.
*/
search(value, node = this.root) {
if (!node) return false;
const nodeValue = node.value;
if (nodeValue === value) {
return true;
}
if (value > nodeValue) {
return this.search(value, node.right);
}
return this.search(value, node.left);
}
/**
* Recursively get the minimum value in the tree.
* @param {BinaryTreeNode} node The current node. Param is not required.
* @return {*} The minimum value.
*/
getMinimum(node = this.root) {
if (!node) return null;
const { left } = node;
if (!left) return node.value;
return this.getMinimum(left);
}
/**
* Recursively get the maximum value in the tree.
* @return {*} The maximum value.
*/
getMaximum(node = this.root) {
if (!node) return null;
const { right } = node;
if (!right) return node.value;
return this.getMaximum(right);
}
}
export default BinarySearchTree;