tree class of Ruby
class Tree
include Enumerable
attr_accessor :left, :right
def initialize(str)
@str = str
end
def each
left.each {|t| yield t } if left
right.each{|t| yield t } if right
yield @str
end
end
t1 = Tree.new('a')
t1.left = Tree.new('a_left')
t1.right = Tree.new('a_right')
t1.left.left = Tree.new('a_left_left')
t1.right.left = Tree.new('a_right_left')
t1.right.right = Tree.new('a_right_right')
t1.each {|t| puts t}
# >> a_left_left
# >> a_left
# >> a_right_left
# >> a_right_right
# >> a_right
# >> a
No comments :
Post a Comment