Skip to content

Instantly share code, notes, and snippets.

@StephanieSunshine
Created June 17, 2015 20:27
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 StephanieSunshine/185b38dc402147ae008c to your computer and use it in GitHub Desktop.
Save StephanieSunshine/185b38dc402147ae008c to your computer and use it in GitHub Desktop.
Simple binary tree in Ruby. I did not write this.
#!/usr/bin/env ruby
# Snipped from: http://www.mikeperham.com/2014/11/26/building-a-binary-tree-with-enumerable/
class Node
include Enumerable
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 }
# just a few of the various operations Enumerable provides
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