Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'prettyprint' # for the p function
- class Tree
- attr_accessor :name
- def initialize name
- @name = name
- @children = []
- end
- def visit visitor
- visitor.visit(self)
- for child in @children
- child.visit(visitor)
- end
- visitor.value
- end
- def << child
- @children << child
- self
- end
- end
- root = Tree.new("root") << (Tree.new("child") << Tree.new("grandkid") << Tree.new("grandkid2")) << Tree.new("child2")
- class Visitor
- attr_accessor :value
- def initialize
- @value = []
- end
- def visit node
- @value << node.name.reverse
- end
- end
- p root.visit(Visitor.new)
Add Comment
Please, Sign In to add comment