-
-
Save philwilt/b7570475666b19a53cef to your computer and use it in GitHub Desktop.
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
class BinarySearchTree | |
constructor: () -> | |
@val = null | |
@size = 0 | |
@right = null | |
@left = null | |
insert: (val) -> | |
if (@val == null) | |
@val = val | |
@size++ | |
return true | |
return false if @val == val | |
if val < @val | |
@left = new BinarySearchTree unless @left | |
@size++ if @left.insert(val) | |
else | |
@right = new BinarySearchTree unless @right | |
@size++ if @right.insert(val) | |
contains: (val) -> | |
return true if @val == val | |
if val < @val | |
return false unless @left | |
@left.contains(val) | |
else | |
return false unless @right | |
@right.contains(val) | |
exports.BinarySearchTree = BinarySearchTree |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The simplicity achieved here are excellent.
I wish I could comment on individual lines...
One edge case might be avoided if you put the early exit for the equality check right at the start of the
insert
function. This will prevent a case where a tree can end up with a size of 3, but no children after this code is run:That will also nicely match the code of the
contains
function.Actually, with that done, you might as well then go ahead and set up the entire
insert
method as anif/else if
block with 4 conditions (equal, null, lesser, greater). Then you can drop the explicitreturn true
statement when saving the value. Implicit return will return the new size, which will always be truthy (since it must be greater than 0). The whole function will then always return the child tree's size (orfalse
), instead of sometimes the size and sometimestrue
. See fork.But that's all just minor nit-picks.
Really really good work boiling this down to it's essence!