-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbst.js
More file actions
123 lines (98 loc) · 2.1 KB
/
bst.js
File metadata and controls
123 lines (98 loc) · 2.1 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/***
Binary Search Tree
A node is represented as:
var node = {
value: null,
left: null,
right: null
}
Methods:
- add(value)
- contains(value)
- remove(value)
- traverse()
- toString()
- toArray()
***/
// constructor
function BinarySearchTree() {
this.root = {
value: null,
left: null,
right: null
};
}
BinarySearchTree.prototype.constructor = BinarySearchTree;
BinarySearchTree.prototype.add = function (value) {
var node = {
value: value,
left: null,
right: null
};
var direction;
function getDirection(current, node) {
if(node.value < current.value) {
return 'left';
} else if (node.value > current.value) {
return 'right';
}
}
function addNode(current, node) {
direction = getDirection(current, node);
if(current[direction] !== null) {
addNode(current[direction], node);
} else {
current[direction] = node;
}
}
// Edge case where BST has no root yet
if(this.root.value === null) {
this.root = node;
} else {
addNode(this.root, node);
}
}
BinarySearchTree.prototype.contains = function(value) {
function findValue(node, value) {
if(value === node.value) {
return true;
} else if(value < node.value) {
return node.left === null ? false : findValue(node.left, value);
} else if(value > node.value) {
return node.right === null ? false : findValue(node.right, value);
}
}
// Start at the root
return findValue(this.root, value);
}
BinarySearchTree.prototype.traverse = function(callback) {
// In-order traversal where left subtree is visited first,
// then the node then its right subtree
function inOrder(node) {
if(node.left !== null) {
// keep going left
inOrder(node.left);
}
callback(node);
if(node.right !== null) {
// keep going right
inOrder(node.right);
}
}
// start at the root
inOrder(this.root);
}
BinarySearchTree.prototype.toString = function() {
var buffer = '';
this.traverse(function(node) {
buffer += node.value;
});
return buffer;
}
BinarySearchTree.prototype.toArray = function() {
var arr = [];
this.traverse(function(node) {
arr.push(node.value);
});
return arr;
}