Tower of Power

Too sweet to be sour.

Displaying N-Deep Trees (Remember Your Algorithms Course?)

Often times when doing web development one has the need to categorize things. And not only basic categorization, n-deep hierarchical categorization. I’ve already discussed storage and retrieval of such data, but there comes a time when one needs to display this information.

Sometimes people build systems to only account for their current requirements. If the software calls for only 2 levels of categorization (Parent and Child only), a simple nested for loop will suffice. However, software requirements change and you’ll soon find yourself up shit creek without a paddle if you need to support 3 or 4 levels of nesting.

For those of us who have formal computer science training, the answer comes rather quickly. To those who’s training is less formal (most web developers I meet have practical training, not formal), I’ll help you out: Tree Traversals (or if you are completely lost, Recursion). If you know absolutely nothing about recursion, I would suggest you familiarize yourself now. A recent, easy to read example can be found here.