-
-
Save fcheung/38211c1b5572ce90931c to your computer and use it in GitHub Desktop.
tr_tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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