Open the Documents folder on your laptop. Inside are the folders Uni and Work, inside Uni there's a folder for each semester, and inside each semester a folder for each course. Data that branches like this doesn't fit neatly in one row of an array.
The structure for branching data is called a tree: there's one node at the top, and every node can have children. In those folders, Documents is the node at the top, and Uni and Work are its children. A binary tree is a tree where every node has at most two children: a left child (left) and a right child (right). It's like a family tree drawn with the ancestors at the top, except that each person (each node) has at most two children.
Root, child and leaf
This is a binary tree with seven nodes:
class TreeNode {
constructor(value, left = null, right = null) {
this.value = value;
this.left = left;
this.right = right;
}
}
const root = new TreeNode(1,
new TreeNode(2, new TreeNode(4), new TreeNode(5)),
new TreeNode(3, new TreeNode(6), new TreeNode(7))
);
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
console.log(root.value); // 1
console.log(root.left.value); // 2
console.log(root.left.right.value); // 5
console.log(root.left.left.left); // null
TreeNodeis a class (a blueprint for objects) for one node, like a linked list node, but it keeps two addresses:leftfor the left child andrightfor the right child.left = nullmeans that if no left child is given, it'snull(there's no child there).new TreeNode(2, new TreeNode(4), new TreeNode(5))makes node 2 with 4 as its left child and 5 as its right child.- The root is the node at the very top, here 1. A tree has only one root.
- Parent and child: 2 is the parent of 4 and 5, and 4 and 5 are children of 2.
- A leaf is a node with no children: 4, 5, 6 and 7.
A binary tree has no rule about values: any number can go anywhere, only the number of children is limited. A tree with the rule "smaller on the left, bigger on the right" is called a binary search tree, the next lesson.
The height of a tree
The height is the number of steps from the root to the farthest leaf. A level is one row of nodes that are the same distance from the root. The tree above has 3 levels (1, then 2 and 3, then 4 to 7), and its height is 2, because getting from 1 to 4 takes just two steps.
Every level can hold twice as many nodes as the level above it: 1, 2, 4, 8 and so on. So a tree of height h has h + 1 levels, and holds at most 2^(h+1) - 1 nodes (2 to the power of h+1, minus 1):
| Height | Levels | Most nodes |
|---|---|---|
| 0 | 1 | 1 |
| 1 | 2 | 1 + 2 = 3 |
| 2 | 3 | 1 + 2 + 4 = 7 |
| 3 | 4 | 1 + 2 + 4 + 8 = 15 |
A balanced tree grows wide, so 1,000 nodes fit in about 10 levels. A one-sided tree, where every node has just one child, is really just a linked list: 1,000 nodes make 1,000 levels. The taller the tree, the longer the walk from the root down.
Be careful, there's a second way to count the height: the number of nodes on the longest path, which equals the number of levels. In the exercise, maxDepth (the greatest depth) counts this way: the tree above gives 3, a single node gives 1, an empty tree gives 0.
A function that calls itself
The left child, together with all the nodes below it, forms a smaller tree: the left subtree. The right child forms the right subtree in the same way. So a function for a tree can work like this: handle this node, then call itself for the left subtree and the right subtree. This is called recursion.
For example, sumValues adds up all the values in a tree:
function sumValues(node) {
if (node === null) return 0;
return node.value + sumValues(node.left) + sumValues(node.right);
}
const small = new TreeNode(1, new TreeNode(2), new TreeNode(3));
console.log(sumValues(small)); // 6
console.log(sumValues(null)); // 0
For the tree small (1 with children 2 and 3):
| Call | What happens | Result |
|---|---|---|
| node 2 | 2 + left null (0) + right null (0) |
2 |
| node 3 | 3 + 0 + 0 | 3 |
| node 1 | 1 + left result (2) + right result (3) | 6 |
Node 1 waits for both its children to answer first, then adds up. The line if (node === null) return 0 is where it stops (an if without curly braces runs just one statement). Every call goes down to a smaller tree, until it finally reaches null, which answers 0 right away without calling again. That's why sumValues, and later countNodes in the exercise, don't run forever, even though they call themselves.
In the exercise, the same pattern is used for two functions:
- Counting nodes (
countNodes): every node adds 1 (notnode.value), plus the left result and the right result. - Counting levels (
maxDepth): this node (1) plus the result of the deeper subtree.Math.max(a, b)gives the bigger of two numbers. - Both answer 0 for
null.
⚠️ Recursion that crashes, or keeps answering 0
- Forgetting to stop at
null. Withoutif (node === null) return 0, the function readsnode.leftfromnull, and you get the error "Cannot read properties of null". - Forgetting to count the node itself.
countNodes(node.left) + countNodes(node.right)on its own always gives 0, because all it adds up is the 0 from eachnull. Add 1 for this node. - Adding both sides for the depth. The depth follows the longest branch, so use
Math.max, not+.
TL;DR: A binary tree is a tree (a data structure that branches) where every node has a value and at most two children: left and right. It has no rule about values. The root is the node at the top, and a leaf is a node with no children. The height is the number of steps from the root to the farthest leaf, and a tree of height h holds at most 2^(h+1) - 1 nodes. A balanced tree (one that grows wide) is short, while a one-sided tree (every node has just one child) is as long as a linked list. Tree functions are usually recursive (they call themselves): answer 0 for null (no node), then combine this node with the results from the left and the right.
⚡ At most two children
Write:
class TreeNode {
constructor(value, left = null, right = null) {
this.value = value;
this.left = left;
this.right = right;
}
}
Meaning: TreeNode is a class (a blueprint for objects) for one node of a binary tree, a tree where every node has at most two children. constructor (the part of the class that sets up the starting values) stores value, the left child left and the right child right in this, the node being made. A child that isn't given is null (no child). The root is the node at the very top, and a leaf is a node with no children. A binary tree has no rule about values.
⚡ The height of a tree
Guess first: the height of a tree is the number of steps from the root to the farthest leaf. What's the most nodes a tree of height 2 can hold?
7, which is 1 + 2 + 4. Every level (row of nodes) can hold twice as many as the level above it, so a tree of height h holds at most 2^(h+1) - 1 nodes.
Meaning: A balanced tree grows wide, so 1,000 nodes fit in about 10 levels. A one-sided tree (every node has just one child) is really just a linked list: 1,000 nodes make 1,000 levels.
⚡ Recursion: stop at null
Write:
function sumValues(node) {
if (node === null) return 0;
return node.value + sumValues(node.left) + sumValues(node.right);
}
Meaning: sumValues adds up all the values in a tree. The left and right children are each the root of a smaller tree (a subtree), so the function calls itself. This is called recursion. null is answered with 0 right away, and that's where the recursion stops. For the depth (the number of levels on the longest path), use Math.max (the bigger number) of the two subtrees' results, not +, then add 1 for this node.