Created
July 13, 2019 17:20
-
-
Save willamesoares/8c989844830ae816fe82c8dd869702d9 to your computer and use it in GitHub Desktop.
JavaScript Binary Search Tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Constructor to create a new Node | |
function Node(key) { | |
this.key = key; | |
this.parent = null; | |
this.left = null; | |
this.right = null; | |
} | |
// Constructor to create a new BST | |
function BinarySearchTree() { | |
this.root = null; | |
} | |
BinarySearchTree.prototype.findLargestSmallerKey = function(num) { | |
let currentNode = this.root; | |
let largestSmallerKey = -1; | |
// This also handles the case the root is null | |
while (currentNode !== null) { | |
// in case the current node key is smaller than the num received | |
// we should consider that as the largest smaller key and move to | |
// the right leaf to try and find a possible new largest smaller key | |
if (currentNode.key < num) { | |
largestSmallerKey = currentNode.key; | |
currentNode = currentNode.right; | |
} else { | |
// in case the current node key is equal or bigger than the num | |
// received we should move to the left to try and find a possible | |
// new largest smaller key | |
currentNode = currentNode.left; | |
} | |
} | |
return largestSmallerKey; | |
} | |
// Creates a new node by a key and inserts it to the BST | |
BinarySearchTree.prototype.insert = function(key) { | |
var root = this.root; | |
// 1. If the tree is empty, create the root | |
if(!root) { | |
this.root = new Node(key); | |
return; | |
} | |
// 2) Otherwise, create a node with the key | |
// and traverse down the tree to find where to | |
// to insert the new node | |
var currentNode = root; | |
var newNode = new Node(key); | |
while(currentNode !== null) { | |
if(key < currentNode.key) { | |
if(!currentNode.left) { | |
currentNode.left = newNode; | |
newNode.parent = currentNode; | |
break; | |
} else { | |
currentNode = currentNode.left; | |
} | |
} else { | |
if(!currentNode.right) { | |
currentNode.right = newNode; | |
newNode.parent = currentNode; | |
break; | |
} else { | |
currentNode = currentNode.right; | |
} | |
} | |
} | |
} | |
/********************************************* | |
* Driver program to test above function * | |
*********************************************/ | |
// Create a Binary Search Tree | |
var bst = new BinarySearchTree(); | |
bst.insert(20); | |
bst.insert(9); | |
bst.insert(25); | |
bst.insert(5); | |
bst.insert(12); | |
bst.insert(11); | |
bst.insert(14); | |
var result = bst.findLargestSmallerKey(17); | |
console.log("Largest smaller number is " + result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment