Skip to content

Instantly share code, notes, and snippets.

@bf4
Created February 15, 2016 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bf4/6ce0c68149c72a29a5e9 to your computer and use it in GitHub Desktop.
Save bf4/6ce0c68149c72a29a5e9 to your computer and use it in GitHub Desktop.
trees
# http://www.mikeperham.com/2014/11/26/building-a-binary-tree-with-enumerable/
class Node
include Enumerable
include Comparable
attr_accessor :data, :left, :right
def initialize(data)
@data = data
end
def each(&block)
left.each(&block) if left
block.call(self)
right.each(&block) if right
end
def <=>(other_node)
data <=> other_node.data
end
end
root = Node.new(3)
root.left = Node.new(2)
root.right = Node.new(1)
root.each {|x| puts x.data }
puts "SUM"
puts root.inject(0) { |memo, val| memo += val.data }
puts "MAX"
puts root.max.data
puts "SORT"
puts root.sort.map(&:data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment