// Adapted from:
// Daniel Shiffman
// Nature of Code: Intelligence and Learning
// https://github.com/shiffman/NOC-S17-2-Intelligence-Learning
// Node in the tree
function Node(val, x, y)
{
this.value = val;
this.left = null;
this.right = null;
// How far apart should the children nodes be
// This will be based on "level" in the tree
this.distance = 2;
this.x = x;
this.y = y;
}
// Search the tree for a value
Node.prototype.search = function(val)
{
console.log ("current " + this.value );
if ( val == this.value ) { console.log ( "found!" ); return this; }
if ( val < this.value )
if ( this.left != null ) { console.log ("go left"); return this.left.search(val); }
else { console.log ("search value lower but nothing to LHS - done"); return null; }
if ( val > this.value )
if ( this.right != null ) { console.log ("go right"); return this.right.search(val); }
else { console.log ("search value higher but nothing to RHS - done"); return null; }
}
Node.prototype.visit = function(parent) // for drawing the graph
{
// Recursively go left
if (this.left != null) { /*console.log ("go left");*/ this.left.visit(this); }
// Draw a line from the parent position (parent not drawn yet)
// console.log( "drawing line from parent " + parent.value + " to this " + this.value);
stroke ("grey");
line( parent.x, parent.y, this.x, this.y );
// Draw a circle
stroke ("blue");
fill("blue");
// console.log ("drawing node " + this.value );
ellipse(this.x, this.y, ellipse_size, ellipse_size);
// Display the value
fill("red");
textAlign(CENTER);
textSize(20);
text ( this.value, this.x, this.y + (ellipse_size/2) );
// Go right
if (this.right != null) { /*console.log ("go right");*/ this.right.visit(this); }
}
// Add a new Node
Node.prototype.addNode = function(n)
{
if (n.value == this.value) return;
if ( SHOWBUILD ) console.log ( "adding node " + n.value + " to current node " + this.value );
if (n.value < this.value)
{
if (this.left == null)
{
if ( SHOWBUILD ) console.log ("put it here on left");
this.left = n;
// Exponentially shrink the distance between nodes for each level
// minus 1/4 of the width
// minus 1/8 of the width
// ....
this.left.x = this.x - (cw / pow(2, n.distance));
this.left.y = this.y + (ch / 10);
}
else
{
if ( SHOWBUILD ) console.log ("go left");
n.distance++; // change node.distance at each level
this.left.addNode(n) // recusively keep going
}
}
else if (n.value > this.value)
{
if (this.right == null)
{
if ( SHOWBUILD ) console.log ("put it here on right");
this.right = n;
this.right.x = this.x + (cw / pow(2, n.distance));
this.right.y = this.y + (ch / 10);
}
else
{
if ( SHOWBUILD ) console.log ("go right");
n.distance++;
this.right.addNode(n);
}
}
};