wrote the tree more object oriented

This commit is contained in:
Christian Bender
2018-03-30 21:15:05 +02:00
parent b9d749acd2
commit c4c5b77420

View File

@ -10,6 +10,8 @@
* bigger.
*/
// class Node
var Node = (function () {
// Node in the tree
function Node(val) {
this.value = val;
@ -27,7 +29,7 @@ Node.prototype.search = function(val) {
return this.right.search(val);
}
return null;
}
};
// Visit a node
Node.prototype.visit = function () {
@ -41,7 +43,7 @@ Node.prototype.visit = function() {
if (this.right != null) {
this.right.visit();
}
}
};
// Add a node
Node.prototype.addNode = function (n) {
@ -58,29 +60,35 @@ Node.prototype.addNode = function(n) {
this.right.addNode(n);
}
}
}
};
// returns the constructor
return Node;
}());
// class Tree
var Tree = (function () {
function Tree() {
// Just store the root
this.root = null;
}
};
// Inorder traversal
Tree.prototype.traverse = function () {
this.root.visit();
}
};
// Start by searching the root
Tree.prototype.search = function (val) {
var found = this.root.search(val);
if(found === null)
{
if (found === null) {
console.log(val + " not found");
}
else {
console.log("Found:" + found.value);
}
}
};
// Add a new value to the tree
Tree.prototype.addValue = function (val) {
@ -90,7 +98,11 @@ Tree.prototype.addValue = function(val) {
} else {
this.root.addNode(n);
}
}
};
// returns the constructor
return Tree;
}());
//Implementation of BST
var bst = new Tree();