-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode.js
64 lines (59 loc) · 1.51 KB
/
node.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
// Daniel Shiffman
// http://codingtra.in
// http://patreon.com/codingtrain
// Binary Tree
// Part 1: https://youtu.be/ZNH0MuQ51m4
// Part 2: https://youtu.be/KFEvF_ymuzY
function Node(val, x, y) {
this.value = val;
this.left = null;
this.right = null;
this.x = x;
this.y = y;
}
Node.prototype.search = function (val) {
if (this.value == val) {
return this;
} else if (val < this.value && this.left != null) {
return this.left.search(val);
} else if (val > this.value && this.right != null) {
return this.right.search(val);
}
return null;
};
Node.prototype.visit = function (parent) {
if (this.left != null) {
this.left.visit(this);
}
// console.log(this.value);
fill(255);
noStroke();
textAlign(CENTER);
text(this.value, this.x, this.y);
stroke(255);
noFill();
ellipse(this.x, this.y, 30, 30);
line(parent.x, parent.y, this.x, this.y);
if (this.right != null) {
this.right.visit(this);
}
};
Node.prototype.addNode = function (n) {
if (n.value < this.value) {
if (this.left == null) {
this.left = n;
this.left.x = this.x - 50;
this.left.y = this.y + 20;
} else {
this.left.addNode(n);
}
} else if (n.value > this.value) {
if (this.right == null) {
this.right = n;
this.right.x = this.x + 50;
this.right.y = this.y + 20;
} else {
this.right.addNode(n);
}
}
};