Last active
December 11, 2015 20:09
-
-
Save yangsu/4653338 to your computer and use it in GitHub Desktop.
Ruby Tree Implementation
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 | |
# Define instance variables children and node_name | |
# and the associated getters and setters | |
attr_accessor :children, :node_name | |
# Define a constructor with 2 parameters, with the second having a default value | |
def initialize(name, children=[]) | |
@children = children | |
@node_name = name | |
end | |
# Uses code blocks | |
def visit_all(&block) | |
visit &block | |
children.each {|c| c.visit_all &block} | |
end | |
# Uses code blocks | |
def visit(&block) | |
block.call self | |
end | |
end | |
tree = Tree.new("root", [ | |
Tree.new('child_a'), | |
Tree.new('child_b'), | |
Tree.new('child_c', [ | |
Tree.new('child_d', [ | |
Tree.new('child_e') | |
]), | |
Tree.new('child_f') | |
]) | |
]) | |
puts "visit single node" | |
tree.visit {|node| puts node.node_name} | |
puts "visit tree" | |
tree.visit_all {|node| puts node.node_name} | |
# Output: | |
# visit single node | |
# root | |
# visit tree | |
# root | |
# child_a | |
# child_b | |
# child_c | |
# child_d | |
# child_e | |
# child_f |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment