203: Trees: Why Use Them?

Why should you consider using trees?

You can find more information about trees in some of the earlier episodes. I’ll try to not repeat the same things here. Episodes 41 and 42 discuss binary trees and left-child right-sibling trees. Episode 54 explains recursion and uses a tree in the examples. And episode 66 explains the composite design pattern which can be thought of as a tree. Listen to these episodes for more details.

Instead of going into more theory about how trees work, at least for now, it’s good to ask why you would want to use a tree in the first place. What problems do trees help you to solve? And what difficulties would you face if you tried to avoid them?

Trees are great at organizing items. Anytime you have a situation where organization can start out in broad terms and then get more specific, then a tree is great.
Maybe you have a store that sells items. You can group them into big top-level groups such as food, furniture, and tools. Then each of these can be further divided into smaller and smaller groups. So maybe you have food, then vegetables, then grains, and finally wheat.

Or you can approach the problem from the other direction and think about where you could put a ruler. It’ll be in tools, certainly. But where in tools? Well, that depends on how many different kinds of tools you have or think you might need to organize. If the only tools that your store sells are rulers and saws, then maybe it doesn’t matter and you can just put them both in tools and be done. But when you start getting so many tools that it becomes hard to find what you’re looking for, then that’s when you need to add extra organization levels to your tree.

Listen to the full episode for more examples and insight. And don’t forget to sign up to be a patron of the podcast by clicking the button at the bottom of the page and selecting your reward level. It doesn’t cost much and you can get some awesome benefits such as actual code reviews to help you write better code. Who knows, maybe you might even find out that your code should be using a tree or something else instead.

No comments yet.

Leave a Reply