-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbinary-search-tree.js
More file actions
70 lines (60 loc) · 1.27 KB
/
binary-search-tree.js
File metadata and controls
70 lines (60 loc) · 1.27 KB
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
// Binary search tree
//
let TreeNode = {
val: null,
left: null,
right: null,
};
class BinarySearchTree {
constructor() {
this._root = null;
}
add(val) {
let newNode = Object.create(TreeNode);
newNode.val = val;
if (this._root == null){
this._root = newNode;
return newNode;
}
(function walkNodes(reference) {
if (newNode.val >= reference.val) {
if (reference.right){
walkNodes(reference.right);
} else {
reference.right = newNode;
return newNode;
}
} else {
if (reference.left){
walkNodes(reference.left);
} else {
reference.left = newNode;
return newNode;
}
}
})(this._root);
}
find(val){
let found = null;
(function findNode(reference) {
if (val === reference.val) {
found = reference;
return;
}
if (val > reference.val) {
findNode(reference.right);
} else {
findNode(reference.left);
}
})(this._root);
return found;
}
}
// let newTree = new BinarySearchTree();
// newTree.add(5);
// newTree.add(10);
// newTree.add(1);
// newTree.add(2);
// let foundNode = newTree.find(2);
// console.log(newTree);
// console.log(foundNode);