Skip to content

Instantly share code, notes, and snippets.

@fcheung
Forked from gagaception/tr_tree.rb
Created October 15, 2015 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcheung/38211c1b5572ce90931c to your computer and use it in GitHub Desktop.
Save fcheung/38211c1b5572ce90931c to your computer and use it in GitHub Desktop.
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