Help with Reverse Tree Traversal using Recursion ..
| From: | Greg Schnippel | Date: | Mon, 14 Nov 2005 13:46:57 +0000 |
| Subject: | Help with Reverse Tree Traversal using Recursion .. | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-225732@lists.php.net to get a copy of this message | ||
I have a large data tree that I wanted to display in an outline
format. I used a textbook tree recursion function to go through the
data and display it as nested unordered lists:
function outputTree($id) {
if (checkChildObjectExists($id)) {
print "<ul>";
$child = getChildArray($id);
foreach ($child as $key => $value) {
print "<li><a
href=\"/object/$key/\">$value</a></li>";
outputTree($key);
}
print "</ul>";
}
}
This works as expected:
> Level 1 (Top)
> Level 2
> Level 3 (Bottom)
However, I also want to display a reverse tree to allow users to trace
their way back up the tree after landing on a lower branch. I tried to
be clever and reverse the function above as:
function outputReverseTree($id) {
if (checkParentExists($id)) {
print "<ul>";
$parent = getParentArray($id);
foreach ($parent as $key => $value) {
print "<li><a
href=\"/object/$key/\">$value</a>\n";
outputReverseTree($key);
}
print "</ul>";
}
}
Which works, but there is something wrong with my logic as the tree
comes back reversed:
> Level 3 (Bottom)
> Level 2
> Level 1 (Top)
Any suggestions on how to do this?
Thanks,
- Greg