in reply to Flat hash to structured
Let's start by saying - you probably don't need recursion to solve this problem. Recursion is nice and it's neat (especially for academic questions) but it can really screw you in the real world. Check out Recursion and subroutine recurse vs goto LABEL for previous discussions. Suffice to say that every problem that can be solved through recursion can also be solved through iteration . Most of the times the recursion solution is more pleasing to view and is easier to follow but at the risk of blowing out stack space after x number of calls into the recursion.
From your description, I believe your initial data structure would look something like this:
$flat = { 0 => { 'parents' => undef, 'children' => [2,3,5] }, 2 => { 'parents' => [0], 'children' => [20,23] }, 3 => { 'parents' => [0], 'children' => [23,30,35] }, 5 => { 'parents' => [0], 'children' => [35,50] }, 20 => { 'parents' => [2], 'children' => [200,223] }, 23 => { 'parents' => [2,3], 'children' => [223,230,233] }, 30 => { 'parents' => [3], 'children' => [233,300,335] }, 35 => { 'parents' => [3,5], 'children' => [335,350] }, 50 => { 'parents' => [5], 'children' => [350,500] }, 200 => { 'parents' => [20], 'children' => undef }, 223 => { 'parents' => [20,23], 'children' => undef }, 230 => { 'parents' => [23], 'children' => undef }, 233 => { 'parents' => [23,30], 'children' => undef }, 300 => { 'parents' => [30], 'children' => undef }, 335 => { 'parents' => [30,35], 'children' => undef }, 350 => { 'parents' => [35,50], 'children' => undef }, 500 => { 'parents' => [50], 'children' => undef }, };
It seems you have all the info you all ready need to answer any type of "tree" question. I don't see the difference between your $top and $flat and your $item and $child1. Will the flat structure not be completely populated?
You can find, directly, the grandkids of a node by doing something like this:
$child = 2; $gks = @{$flat->{$flat->{$child}{children}[0]}{children}}; print join( ', ', @$gks ), "\n";
If you really want to store this data in a tree, check out some of the tree modules on CPAN .
-derby
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Flat hash to structured
by traveler (Parson) on Dec 27, 2001 at 01:43 UTC | |
by tame1 (Pilgrim) on Dec 27, 2001 at 20:01 UTC |