Created
February 15, 2015 08:58
-
-
Save TheIronDev/372c5e2288c40c4973ca to your computer and use it in GitHub Desktop.
Quick BST Implementation
This file contains 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
var BST = function(arr){ | |
var length = arr.length, | |
middle = length % 2 === 0 ? length/2 : (length -1)/2; | |
this.value = arr[middle]; | |
if(length > 1) { | |
this.left = new BST(arr.slice(0, middle )); | |
this.right = new BST(arr.slice((middle + 1), length)); | |
} | |
} | |
BST.prototype.search = function(value) { | |
if (this.value === value) { | |
return value; | |
} else if(this.left && this.value > value) { | |
return this.left.search(value); | |
} else if (this.right && this.value < value) { | |
return this.right.search(value); | |
} else { | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment