我有一个由parent_id和child_id组成的分支模型。我想要获得一个父/子关系数组,而不是查询每个父/子关系的子关系。
对于此表:
Parent_id | Child_id
1 | 2
1 | 6
1 | 9
2 | 3
3 | 10
4 | 7我想要得到1的孩子,他的孩子的孩子是这样的:
{2 => {3 => {10}}, 6, 9}而不向每个父代查询其子代。
有没有一种算法可以有效地实现这一点,或者我需要遍历每个父级?谢谢。
发布于 2011-11-07 00:15:28
呼吸优先的搜索将会完成这项工作。
def build_tree(i, edges)
list = {}
out_nodes = edges.select {|e| e[0] == i}.map {|e| e[1]}.uniq
out_nodes.each {|n| list[n] = build_tree(n, edges)}
list
end
edges = [[1,2],[1,6],[1,9],[2,3],[3,10],[4,7]]
puts build_tree(1, edges)
# {2=>{3=>{10=>{}}}, 6=>{}, 9=>{}}发布于 2011-11-07 00:17:30
函数式和递归方法:
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)
#=> {6=>{}, 2=>{3=>{10=>{}}}, 9=>{}}不使用facet进行编辑(现在您将看到我为什么要使用它了!):
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)
endhttps://stackoverflow.com/questions/8028211
复制相似问题