Skip to content

Instantly share code, notes, and snippets.

@fcheung
Forked from gagaception/tr_tree.rb
Created Oct 15, 2015
Embed
What would you like to do?
tr_tree
class Tree
attr_accessor :payload, :children
def initialize(payload, children = [])
@payload = payload
@children = children
end
def traverse(&block)
yield self
@children.each {|child| child.traverse(&block)}
end
end
# The "Leafs" of a tree, elements that have no children
fifth_node = Tree.new(5, [])
eleventh_node = Tree.new(11, [])
fourth_node = Tree.new(4, [])
# The "Branches" of the tree
ninth_node = Tree.new(9, [fourth_node])
sixth_node = Tree.new(6, [fifth_node, eleventh_node])
seventh_node = Tree.new(7, [sixth_node])
fifth_node = Tree.new(5, [ninth_node])
# The "Trunk" of the tree
trunk = Tree.new(2, [seventh_node, fifth_node])
trunk.traverse{|tree| puts tree.payload}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment