Weaknesses (in my mind):
- Walking up the tree and then down again
- Using an array to store the relationships and then looping (posibly repeatedly) over that array to get the tree
- Pathological case: linked list described tail first (you'll walk all the way back and then all the way forward again)
- Pathological case: input discribing 2 disjoint trees (your format is flexible). Your code will likely loop FOREVER. It is an error to enter that, but you should still return.
I think you could do it much more efficiently with a hash. Something to the effect of:
my %nodes = ();
foreach my $tuple (split ',', $s) {
# shorter spliting
my ($child, $parent) = split ' ', $tuple;
# init nodes if not already done
$nodes{$child} ||= { node => $child, children => []};
$nodes{$parent} ||= { node => $parent, children => []};
# insert relationship
push @{$nodes{$parent}{children}}, \$nodes{$child}
$nodes{$child}{parent} = $parent;
}
Then you could walk up the tree to get the root and already have a built tree.
Update: your format is flexible enough to describe any directed graph. It is a reasonable expectation that code manipulating such data should halt for any acyclic input.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.