// Cloned by Evans Kipchaui on 13 Oct 2023 from World "Binary tree (clone by Kaushal)" by Kaushal
// Please leave this clone trail here.
// Cloned by Kaushal on 7 Oct 2023 from World "Binary tree" by "Coding Train" project
// Please leave this clone trail here.
// Modified port of "01_binary_tree_viz" from AI course by Daniel Shiffman
// https://github.com/nature-of-code/NOC-S17-2-Intelligence-Learning/tree/master/week1-graphs
// Daniel Shiffman
// Nature of Code: Intelligence and Learning
// https://github.com/shiffman/NOC-S17-2-Intelligence-Learning
// canvas size
const cw = 900;
const ch = 600;
const root_x = cw / 2;
const root_y = ch / 10;
const ellipse_size = cw / 25;
// range of numbers
const MAX = 100000000;
// how many nodes
const NUMBER_OF_NODES = MAX / 1000000;
// console log how we build the tree or not
const SHOWBUILD = true;
// Binary tree
var tree;
/**
* This method counts the number of node in the Tree
* @param {rootNode} Root node of the Tree
*/
function countNodes(rootNode) {
var count = 0;
// If instance is null, skip traversal and return default 0
if (!!rootNode) {
var nodeQueue = [];
nodeQueue.push(rootNode);
// Keep adding in queue till we find any node.
while(nodeQueue.length > 0)
{
if(!!nodeQueue[0].left) {
nodeQueue.push(nodeQueue[0].left);
}
if(!!nodeQueue[0].right) {
nodeQueue.push(nodeQueue[0].right);
}
count++;
nodeQueue.shift();
}
}
return count;
}
function setup()
{
createCanvas(cw,ch);
$.getScript ( "/uploads/codingtrain/node.js", function() {
// console.log ("Got node");
$.getScript ( "/uploads/codingtrain/tree.js", function() {
// console.log ("Got tree");
// New tree
tree = new Tree();
console.log ("=== build tree =================");
// Add random values
for (var i = 0; i < NUMBER_OF_NODES; i++)
{
var n = floor(random(0, MAX));
// console.log ("adding node: " + n);
tree.addValue(n);
}
background("lightblue");
// Traverse the tree
// tree.traverse();
// Calculate number of node in this tree.
console.log ("Number of node in this Tree are " + countNodes(tree.root));
// Search the tree for random number
var x = floor(random(0, MAX));
AB.msg( "console log shows how we search a sorted tree quickly <br> search tree for " + x + "<br>" );
console.log ( "=== search tree for " + x + " ===================");
var result = tree.search(x);
if (result === null) AB.msg('not found', 2);
else AB.msg('found', 2);
} );
} );
}