Skip to content

Instantly share code, notes, and snippets.

@jasonseminara
Last active August 29, 2015 14:01
Show Gist options
  • Save jasonseminara/17a85346594b545f2e59 to your computer and use it in GitHub Desktop.
Save jasonseminara/17a85346594b545f2e59 to your computer and use it in GitHub Desktop.
first coffeescript
bst=(r)->
_root = r
compare=(a,b)->
return switch
when a is b then 0
when a < b then -1
when a > b then 1
root:()->_root
bstNode:(d)->
left:null
right:null
data:d
walk: (node,f,traversalType='in')->
if node?
switch traversalType
when 'in'
@walk(node.left,f,'in')
f node
@walk(node.right,f,'in')
when 'pre'
f node
@walk(node.left,f,'pre')
@walk(node.right,f,'pre')
when 'after'
@walk(node.left,f,'after')
@walk(node.right,f,'after')
f node
when 'desc'
@walk(node.right,f,'desc')
f node
@walk(node.left,f,'desc')
else
@walk(node.left,f,'in')
f node
@walk(node.right,f,'in')
return
insert: (num) ->
#console.log arguments
return _root = @bstNode num if !_root
find_insertion_point = (curr,num,dir) =>
return tree_insert curr[dir], num if curr[dir]?
curr[dir] = @bstNode num
return curr[dir]
tree_insert = (curr,num)->
return switch compare num , curr.data
when 0 then curr
when -1 then find_insertion_point curr, num, 'left'
when 1 then find_insertion_point curr, num, 'right'
#console.log(_root)
tree_insert(_root, num)
node_count: ->
counter=0
@walk(_root,-> ++counter)
toArray:(order='asc') ->
arr=[]
pushItem = (i) -> arr.push i.data
switch order
when 'asc','in' then @walk( _root, pushItem, 'in')
when 'desc' then @walk( _root, pushItem, 'desc')
when 'pre' then @walk( _root, pushItem, 'pre')
when 'after' then @walk( _root, pushItem, 'after')
else @walk( _root, pushItem, 'in')
arr
Q = bst()
Q.insert 99
Q.insert 50
Q.insert 9
Q.insert 8
Q.insert 5
Q.insert 100
Q.insert 6
Q.insert 3
Q.insert 990
Q.insert 56
Q.insert 54
console.log Q.insert 989
console.log Q.root()
console.log Q.toArray()
console.log Q.toArray 'desc'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment