All episodes · From a List to Your Map App · Episode 11

Trees in Code: Folders, Formulas, Traversals

Pressing play loads the video from YouTube.

The folders on your computer and a formula like (3 + 4) × 5 have the same shape inside: a tree, one root branching down with no loops.
We learn the words (root, children, leaves, depth, binary tree), turn the formula into a tree, walk it four classic ways (preorder, inorder, postorder and level order), watch postorder work out the answer, 35, and see two ways to store a tree in code: with pointers, or packed into an array.

Every animation in this video is drawn by code, and the narration is an AI voice.

Transcript

Every folder on your computer sits inside another folder, all the way up to one at the top. And a formula like three plus four, times five, has the same shape inside. That shape is a tree.

A tree starts at one root and branches downward. Each point is a node, and no path ever loops back up. The nodes right below a node are its children. Nodes with no children are leaves, and how many steps a node is from the root is its depth. In a binary tree, every node has at most two children: a left one and a right one.

Now the formula. The operations go on top, and the numbers sit at the leaves. The plus is lower down, so it happens first. The tree's shape already holds the brackets.

There are four classic ways to visit every node. Three of them are recursion, from episode four: handle each side the same way as the whole tree. Preorder visits the node first, then its left side, then its right. Inorder goes left, node, right. That spells out the formula the way we write it. Postorder does both sides first and the node last. Each operation then finds its two numbers ready, and out comes the answer: thirty-five. And level order simply goes one row at a time, from the top down.

In code, each node usually keeps two pointers, one for each child, like the linked list in episode two. But when every row is full, you can drop the pointers and line the tree up in an array. The node at position i keeps its children at two i plus one, and two i plus two.

Trees branch down from one root and never loop back. Walk them in the right order, and they do real work, like solving a formula. Next time: a tree that keeps everything in order, so finding a number is one walk from the root down to a leaf. See you there.

Next episode: binary search trees, where finding a number is one walk from the root down to a leaf.

Buy the Developer a Coffee

Entirely up to you: it works the same either way.

Every cup turns into the next update.

WeChat Pay QR code
WeChat Pay
Alipay QR code
Alipay
PayPal QR code
PayPal