Created
February 15, 2016 16:48
-
-
Save bf4/6ce0c68149c72a29a5e9 to your computer and use it in GitHub Desktop.
trees
This file contains 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
# 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