一种功能性和递归的方法:
require 'facets'
def create_tree(pairs, root)
relationships = pairs.map_by { |parent, child| [parent, child] }
get_children = proc do |parent|
(relationships[parent] || []).mash do |child|
[child, get_children.call(child)]
end
end
get_children.call(root)
end
pairs = [[1, 2], [1, 6], [1, 9], [2, 3], [3, 10], [4, 7]]
p create_tree(pairs, 1)
[编辑] 没有facets(现在你将会明白我使用它的原因!):
def create_tree(pairs, root)
relationships = Hash[pairs.group_by { |p, c| p }.map { |p, ary| [p, ary.map { |p, c| c }] }]
get_children = proc do |parent|
Hash[(relationships[parent] || []).map do |child|
[child, get_children.call(child)]
end]
end
get_children.call(root)
end