UNPKG

mjbinarytree

Version:

Binary Search Tree implementation

78 lines (64 loc) 1.53 kB
function Node(val){ this.value = val; this.left = null; this.right = null; } function BinarySearchTree(){ this.root = null; } var bst=null; exports.CreateTree = function() { bst = new BinarySearchTree(); console.log(" New Tree Created"); return ""; } exports.pushToTree = function(value) { bst.push(value); console.log(""); return"" ; } BinarySearchTree.prototype.push = function(val){ var root = this.root; if(!root){ this.root = new Node(val); return; } var currentNode = root; var newNode = new Node(val); while(currentNode){ if(val < currentNode.value){ if(!currentNode.left){ currentNode.left = newNode; console.log(newNode.value+" new node to left"); break; } else{ currentNode = currentNode.left; console.log(currentNode.value+" new node to left"); } } else{ if(!currentNode.right){ currentNode.right = newNode; console.log(newNode.value+" new node to right"); break; } else{ currentNode = currentNode.right; console.log(currentNode.value+" new node to right"); } } } } exports.Depthfirstsearch = function() { dfs(bst.root); console.log(" //Depth First Search"); return"" ; } function dfs(node){ if(node){ console.log(node.value); dfs(node.left); dfs(node.right); } }