xxxxxxxxxx
63
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
this.x = 0;
this.y = 0;
this.level = 0;
}
Node.prototype.addNode = function(node) {
node.level = this.level + 1;
const dx = width / (pow(2, node.level + 1));
if (node.value < this.value) {
if (this.left === null) {
this.left = node;
this.left.x = this.x - dx;
this.left.y = this.y + 50;
} else {
this.left.addNode(node);
}
}
if (node.value > this.value) {
if (this.right === null) {
this.right = node;
this.right.x = this.x + dx;
this.right.y = this.y + 50;
} else {
this.right.addNode(node);
}
}
}
Node.prototype.visit = function(parent) {
if (this.left !== null) {
this.left.visit(this);
}
if (this.right !== null) {
this.right.visit(this);
}
if (parent) {
stroke(200);
line(this.x, this.y, parent.x, parent.y);
}
stroke(0);
fill(0);
ellipse(this.x, this.y, 20, 20);
fill(255);
noStroke();
textAlign(CENTER);
text(this.value, this.x, this.y + 5);
}
Node.prototype.search = function(value) {
if (this.value > value && this.left !== null) {
return this.left.search(value);
}
if (this.value == value) {
return this;
}
if (this.value < value && this.right !== null) {
return this.right.search(value);
}
}