-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbst.js
71 lines (60 loc) · 1.28 KB
/
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
61
62
63
64
65
66
67
68
69
70
71
function BSTNode(data, depth) {
this.count = 1;
this.data = data;
this.depth = depth;
this.leftChild = null;
this.rightChild = null;
}
function BST() {
this.root = null;
}
BST.prototype.add = function add(value) {
if (this.root) {
this.root.add(value, 0);
} else {
this.root = new BSTNode(value, 0);
}
};
BST.prototype.traverse = function traverse(value) {
const order = [];
if (this.root) {
this.root.traverse(order);
}
return order;
};
BSTNode.prototype.traverse = function traverse(arr) {
if (this.leftChild) {
this.leftChild.traverse(arr);
}
arr.push({ value: this.data, depth: this.depth });
if (this.rightChild) {
this.rightChild.traverse(arr);
}
};
BSTNode.prototype.add = function add(value, depth) {
if (value < this.data) {
if (this.leftChild) {
this.leftChild.add(value, depth + 1);
} else {
this.leftChild = new BSTNode(value, depth + 1);
}
} else if (value > this.data) {
if (this.rightChild) {
this.rightChild.add(value, depth + 1);
} else {
this.rightChild = new BSTNode(value, depth + 1);
}
} else {
this.count++;
}
};
const bst = new BST();
bst.add(10);
bst.add(5);
bst.add(14);
bst.add(9);
bst.add(11);
bst.add(1);
bst.add(12);
bst.add(6);
console.log(bst.traverse());