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.