-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbst.js
119 lines (107 loc) · 2.82 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
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
class BST {
constructor() {
this.empty = true;
}
add(value) {
if (this.empty) {
this.empty = false;
this.value = value;
this.left = new BST();
this.right = new BST();
} else {
if (value < this.value) {
this.left.add(value);
} else {
this.right.add(value);
}
}
}
set(value, left, right) {
this.empty = false;
this.value = value;
this.left = left;
this.right = right;
}
display() {
if (this.empty) {
return `empty node`;
} else {
return `${this.value}`;
}
}
contains(value) {
if (this.empty) {
return false;
} else {
return this.value === value || this.left.contains(value) || this.right.contains(value);
}
}
rotateLeft() {
if (this.right.empty) {
alert("Cannot rotate left");
} else {
let A = this.left;
let B = this.right.left;
let C = this.right.right;
let P = this.value;
let Q = this.right.value;
let newP = new BST();
newP.set(P, A, B);
this.set(Q, newP, C);
}
}
rotateRight() {
if (this.left.empty) {
alert("Cannot rotate right");
} else {
let A = this.left.left;
let B = this.left.right;
let C = this.right;
let P = this.left.value;
let Q = this.value;
let newQ = new BST();
newQ.set(Q, B, C);
this.set(P, A, newQ);
}
}
nodes(x, y, a, b) {
if (this.empty) {
return [];
} else {
let nodes = [
{
value: this.display(),
origX: x,
origY: y,
x,
y
}
];
nodes = nodes.concat(this.left.nodes(x - a, y + b, a / 1.2, b));
nodes = nodes.concat(this.right.nodes(x + a, y + b, a / 1.2, b));
return nodes;
}
}
links() {
if (this.empty) {
return [];
} else {
let links = [];
if (!this.left.empty) {
links.push({
source: this.display(),
target: this.left.display()
});
}
if (!this.right.empty) {
links.push({
source: this.display(),
target: this.right.display()
});
}
links = links.concat(this.left.links());
links = links.concat(this.right.links());
return links;
}
}
}