Skip to content

Instantly share code, notes, and snippets.

@philwilt
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save philwilt/b7570475666b19a53cef to your computer and use it in GitHub Desktop.
Save philwilt/b7570475666b19a53cef to your computer and use it in GitHub Desktop.
binary search tree
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
@brookr
Copy link

brookr commented Nov 2, 2014

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:

bst = new BinarySearchTree();
bst.insert(null);
bst.insert(null);
bst.insert(null);

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 an if/else if block with 4 conditions (equal, null, lesser, greater). Then you can drop the explicit return 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 (or false), instead of sometimes the size and sometimes true. See fork.

But that's all just minor nit-picks.

Really really good work boiling this down to it's essence!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment