Photo by Filip Zrnzević on Unsplash

Tree Basics

I’m someone who enjoys working with linear data. A good old-fashioned numbered to-do list feels very comfortable to me. Move from one thing to the next, and if you need to jump ahead you have a handy way of doing that with the numbers.

Arrays are the numbered lists of the programming world, but unfortunately, they can’t be used for all of our data storage needs. What if we need some sort of decision-making structure. Let’s say if the answer to a question is yes we go one way and for no, we go the other way. We could represent the data like this.

An engineer’s guide to fixing things

Visualizing something small like this is pretty easy and having a real-world connection like a decision-making process is a great application for a tree.

Trees, Programmatically organize data in a non-linear way. The information in a tree is stored hierarchically. Relationships are described in the following ways.

Quick Definitions:

Root: The start of a tree. There are no parent nodes above the root

Key: The value or piece of data we are storing in each node

Edge: The connector/pointer that connects two nodes and reflects their relationship.

Siblings: Two nodes that share a parent node.

Parent: A node that points to other nodes ( it’s children)

Child / Children: Nodes that are pointed to by another node (its parent)

Subtree: A portion of a tree that also fulfills the requirements to be a tree.

Leaf Nodes: Nodes that do not have any children.

Height: The number of ‘levels’ or amount of nesting a tree has.

So Where do we use Trees?

Whelp, if you are viewing this in a browser the DOM or document object model is an HTML tree.

Let’s use the body as our example root.

It has one child <div class'first'>

Both <div> elements with a class of second are siblings to one another.

<div class='third'> is a leaf.

Trees are a common non-linear data structure that can emulate many real-world situations. I’m going to write another post about probably the most talked-about type of tree a binary tree which has all the elements of a tree with a few unique conditions. There I will show you some methods for traversing a tree and getting the most out of this data structure.




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Robert K.

Full- Stack Software Engineer with a former life in high-end restaurant management. Currently working in React JS and Ruby on Rails.