$ wget -q -O - http://files.smidsrod.no/gen_ul_tree.pl.txt | perl -It should look something like this:
The template code code is fairly well commented, so it shouldn't be necessary to explain here what it does.
Now go out and make some nice treeviews on your web pages. And while you're at it, sprinkle some jQuery on top of it to make it interactive.
Update (2020-10-09): Ben Brumm contacted me and suggested linking to an article about storing hierarchical data in SQL. It describes several different methods of storing and querying the tables, with different pros and cons.