Created
June 17, 2015 20:27
-
-
Save StephanieSunshine/185b38dc402147ae008c to your computer and use it in GitHub Desktop.
Simple binary tree in Ruby. I did not write this.
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
#!/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