Cha*_*son 3 ruby tree hierarchical-data
我有以下平树:
id name parent_id is_directory
===========================================================
50 app 0 1
31 controllers 50 1
11 application_controller.rb 31 0
46 models 50 1
12 test_controller.rb 31 0
31 test.rb 46 0
Run Code Online (Sandbox Code Playgroud)
我试图找出一个算法,将其纳入以下树结构:
[{
id: 50,
name: app,
is_directory: true
children: [{
id: 31,
name: controllers,
is_directory: true,
children: [{
id: 11,
name: application_controller.rb
is_directory: false
},{
id: 12,
name: test_controller.rb,
is_directory: false
}],
},{
id: 46,
name: models,
is_directory: true,
children: [{
id: 31,
name: test.rb,
is_directory: false
}]
}]
}]
Run Code Online (Sandbox Code Playgroud)
有人能指出我正确的方向吗?我正在寻找步骤(例如,构建一个关联数组;遍历数组寻找x;等等).
我正在使用Ruby,因此我可以使用面向对象的语言功能.
Dan*_*ley 15
在ruby中,您应该能够使用Hash 在线性时间O(n)中轻松完成.
# Put all your nodes into a Hash keyed by id This assumes your objects are already Hashes
object_hash = nodes.index_by {|node| node[:id]}
object_hash[0] = {:root => true}
# loop through each node, assigning them to their parents
object_hash.each_value {|node|
continue if node[:root]
children = object_hash[node[:parent_id]][:children] ||= []
children << node
}
#then your should have the structure you want and you can ignore 'object_hash' variable
tree = object_hash[0]
Run Code Online (Sandbox Code Playgroud)