Skip to content

Instantly share code, notes, and snippets.

@nkpart
Created September 8, 2008 02:52
Show Gist options
  • Save nkpart/9365 to your computer and use it in GitHub Desktop.
Save nkpart/9365 to your computer and use it in GitHub Desktop.
class TreeBuilder
def build a
root_node = Node.new(a)
yield root_node if block_given?
root_node.as_tree
end
class Node
def initialize value
@value = value
@children = []
end
def as_tree
(@children.empty?) ? @value : [@value, @children.map(&:as_tree)]
end
def child c
new_node = Node.new(c)
@children << new_node
yield new_node if block_given?
end
end
end
builder = TreeBuilder.new
results = builder.build(1) do |root|
root.child(2)
root.child(3) do |three|
three.child(4)
end
end
p results
# <= [1, [2, [3, [4]]]]
class TreeWalker
def walk tree, &combine_func
root, children = *tree
inner_walk root, children, &combine_func
end
private
def inner_walk root, children, &combine_func
children ||= []
combined_children = children.map { |c|
r, cc = *c
inner_walk combine_func.call(root, r), cc, &combine_func
}
[root] + combined_children
end
end
p TreeWalker.new.walk(results) { |p, c| [p,c].join(',') }
# <= [1, ["1,2"], ["1,3"], ["1,3,4"]]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment