Data Structures & Algorithms / Module 6: Trees
Topic 6.1
Trees and traversal
Branching data, and four ways to visit every node once.
Watch: the tree is the same; only when each part is noted down changes. Compare the order row below for all four buttons.
- moving now
- passed / marked
- finished / the result
Trees are everywhere
You use trees every day without calling them that:
- Folders on your computer: a folder holds files and other folders.
- Web pages: the DOM is a tree, with
<html>as its root. - Comments with replies, nested menus, org charts, nested JSON.
Some terms: the root is the top node, a leaf is a node with no children, and the height is the number of levels from the root to the furthest leaf. In a binary tree, every node has at most two children: left and right.
Depth-first: three orders
All three walk the same way: down the left, then the right. The only difference is when a node is recorded. Try all three buttons in the figure and watch the order row in front.
Code, for programmersOne function, three places to visit
function walk(node, visit) {
if (!node) return; // base case: an empty spot
// visit(node); // pre-order: before the children
walk(node.left, visit);
// visit(node); // in-order: between left and right
walk(node.right, visit);
// visit(node); // post-order: after both children
}- Pre-order: parent before children. Used to copy or print a structure, such as listing a folder with indentation.
- In-order: on a binary search tree, it comes out sorted, smallest to largest.
- Post-order: children before parent. Used when a parent needs its children's results: a folder's size, or deleting a folder and everything in it.
Breadth-first: level by level
Level-order uses a queue (Module 1): take a node from the front, record it, then add its children to the back. Because a queue is fair (first in, first out), every node on level 1 is handled before level 2. Choose this when you want whatever is nearest the root, such as first-level replies to a comment.
Code, for programmersLevel-order
function levelOrder(root) {
const out = [], queue = [root];
while (queue.length) {
const node = queue.shift(); // for big trees use a real queue: shift() is O(n)
out.push(node.value);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
return out;
}Quiz
Working out a folder's total size (files + subfolders). Which order fits best?
In-order traversal of a binary search tree gives…
Which data structure does level-order traversal use?
0 of 3 answered.