Open NicholasClaudio opened 5 years ago
So I can do the BST? I was waiting for approval to post the code.
var tree;
function setup() { tree = new Tree(); tree.addValue(5); //hard coded values to put into the tree tree.addValue(3); tree.addValue(1); tree.addValue(7); tree.addValue(6); tree.addValue(15); console.log(tree); tree.traverse(); // this will display the values inside the tree. }
function Node(val) { this.value = val; this.left = null; this.right = null; } function Tree() { this.root = null; }
Tree.prototype.traverse = function() { this.root.visit(); }
Tree.prototype.search = function(val) { var found = this.root.search(val); return found; }
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); } console.log(' Value not found'); return null; }
Node.prototype.visit = function() { if (this.left != null) { this.left.visit(); } console.log(this.value); if (this.right != null) { this.right.visit(); } }
Tree.prototype.addValue = function(val) { //creates new node from value var n = new Node(val); if (this.root == null) { this.root = n; } else { this.root.addNode(n); } }
Node.prototype.addNode = function(n) { if (n.value < this.value) { //these statements compare the value coming in to if (this.left == null) { //determine where they will be placed within the tree. this.left = n; } else { this.left.addNode(n); } } else if (n.value > this.value) { if (this.right == null) { this.right = n; } else { this.right.addNode(n); } } }
setup();
Requesting to do a Binary Tree to go alongside the Binary Search Tree.