Skip to content

Instantly share code, notes, and snippets.

@syou6162
Created February 14, 2012 10:48
Show Gist options
  • Save syou6162/1825745 to your computer and use it in GitHub Desktop.
Save syou6162/1825745 to your computer and use it in GitHub Desktop.
Treeのオブジェクトに対してeachでごにょごにょしたいときのテンプレート的な何か
class Tree
attr_accessor :val, :level, :l, :r
def initialize(val, level, l, r)
@val = val; @level = level; @l = l; @r = r
end
def each
stack = []
stack.push self
explored = []
while !stack.empty?
u = stack.shift
if !explored.include?(u)
explored.push u
yield u
stack.unshift u.l unless u.l.nil?
stack.unshift u.r unless u.r.nil?
end
end
end
end
tree = Tree.new("World", 0,
Tree.new("Asia", 1,
Tree.new("Japan", 2, nil, nil),
Tree.new("China", 2, nil, nil)),
Tree.new("Europe", 1,
Tree.new("Dutch", 2, nil, nil),
Tree.new("Portugal", 2, nil, nil)))
tree.each {|node|
puts "\s" * node.level + node.val
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment