Algorithm for parsing a flat tree into a non-flat tree
Posted
by Chad Johnson
on Stack Overflow
See other posts from Stack Overflow
or by Chad Johnson
Published on 2010-05-13T17:03:07Z
Indexed on
2010/05/13
17:14 UTC
Read the original article
Hit count: 423
tree
|hierarchical-data
I have the following flat tree:
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
and I am trying to figure out an algorithm for getting this into the following tree structuree:
[{
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
}]
}]
}]
Can someone point me in the right direction? I'm looking for steps (eg. build an associative array; loop through the array looking for x; etc.).
© Stack Overflow or respective owner