Skip to content

Instantly share code, notes, and snippets.

@yangsu
Last active December 11, 2015 20:09
Show Gist options
  • Save yangsu/4653338 to your computer and use it in GitHub Desktop.
Save yangsu/4653338 to your computer and use it in GitHub Desktop.
Ruby Tree Implementation
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