Suppose you need the deepest folder in a nested folder structure, such as a project’s directory tree read into memory. Here is a recursive function that counts the folders on the longest path down, with a benchmark and a few deep inputs. Save it as opening-slow.ts:
// Opening problem: how deep is the deepest folder? The recursive version: node opening-slow.ts
import { bench } from "./bench.ts";
import { deepChain, wideTree, type Folder } from "./folders.ts";
// The number of folders on the longest path from `folder` down, counting `folder`.
// O(n) time; one call per level, so O(h) memory on the call stack for a tree h folders deep.
export function maxDepth(folder: Folder): number {
let deepest = 0;
for (const child of folder.children) deepest = Math.max(deepest, maxDepth(child));
return deepest + 1;
}
if (process.argv[1] === import.meta.filename) {
bench("recursive maxDepth, wide tree", [100_000, 200_000, 400_000], (n) => wideTree(n), maxDepth);
for (const depth of [1_000, 5_000, 10_000, 20_000]) {
console.log(`chain of ${depth}:`, maxDepth(deepChain(depth)));
}
}
In one run, it walked a tree of 400,000 folders in 6.38 ms. But a chain of 20,000 folders, each nested inside the one before, crashed the process with RangeError: Maximum call stack size exceeded. This module shows why, walks trees in two ways that don’t crash, then builds a binary search tree and shows why sorted input makes it slow.
After this module, you can:
- walk a tree depth first with recursion and with your own stack, and say how deep recursion can go in Node.js
- walk a tree breadth first, one level at a time, with a queue
- say what a binary search tree costs per operation, and why keys that arrive in sorted order make it slow
- read a binary search tree’s keys in sorted order, and use that to answer range questions
Folders form a tree
Make a folder for the module, as in Module 1, and copy bench.ts into it unchanged. Copy deque.ts from Module 5 as well, because a later section uses its Deque:
mkdir module-06 && cd module-06 && echo '{ "type": "module" }' > package.json
Then copy folders.ts from the module-06 folder of the course repository. That folder also holds every full file this module shows in part. Here is the folder type:
// excerpt from folders.ts
export type Folder = { name: string; size: number; children: Folder[] };
The file also has two builders for test inputs:
deepChain(n)puts every folder inside the one before it, n folders in all.wideTree(n)gives every folder 4 subfolders, level by level, until it has n folders.
A folder holds a list of subfolders, and each subfolder holds its own list. That shape is a tree: a set of items, called nodes, where every node but one has exactly one parent. The node with no parent is the root, and following parents from any node always leads to it.
Figure 1 draws a small folder tree. This module uses it for every trace. Lines are links from a parent to its children.
[home]
/ \
[docs] [photos]
/ \ \
[tax] [old] [2024]
depth 1 home
depth 2 docs, photos
depth 3 tax, old, 2024
Figure 1: every folder has one parent, except the root, so each folder sits at exactly one depth.
The depth of a folder is the number of folders on the path from the root down to it, so the root has depth 1. So the opening’s maxDepth returns the largest depth, which is 3 for this tree.
Measure the recursive walk
The height of a tree is the largest depth in it. wideTree(n) is a short tree. With 4 subfolders per folder, its height is only about log₄(n) + 1. deepChain(n) is as tall as a tree can be, because its height is n.
Pause and predict. The benchmark doubles the wide tree from 100,000 to 400,000 folders. How does the time grow? Then the chains get 1,000, 5,000, 10,000 and 20,000 folders deep. Which ones print?
Here is what node opening-slow.ts printed, with the file paths shortened:
recursive maxDepth, wide tree
n median ms x prev
100,000 1.88
200,000 3.51 1.9
400,000 6.38 1.8
chain of 1000: 1000
chain of 5000: 5000
chain of 10000: 10000
file:///.../module-06/opening-slow.ts:7
export function maxDepth(folder ) {
^
RangeError: Maximum call stack size exceeded
at maxDepth (file:///.../module-06/opening-slow.ts:7:25)
at maxDepth (file:///.../module-06/opening-slow.ts:9:68)
at maxDepth (file:///.../module-06/opening-slow.ts:9:68)
at maxDepth (file:///.../module-06/opening-slow.ts:9:68)
at maxDepth (file:///.../module-06/opening-slow.ts:9:68)
at maxDepth (file:///.../module-06/opening-slow.ts:9:68)
at maxDepth (file:///.../module-06/opening-slow.ts:9:68)
at maxDepth (file:///.../module-06/opening-slow.ts:9:68)
at maxDepth (file:///.../module-06/opening-slow.ts:9:68)
at maxDepth (file:///.../module-06/opening-slow.ts:9:68)
Node.js v26.13.1
Every table in this module comes from one run on an Intel Core i7-9750H laptop (x86_64, 6 cores, macOS) with Node.js 26.13.1. Your numbers will differ, but the ratios should look alike. (The odd spaces in the error are explained in “Going deeper”.)
On the wide tree, the time grew about 2 times per doubling. Each folder is one call that reads its children once, so maxDepth is O(n) time. But on the chain, every call waits for its child’s call to return, so a chain of 20,000 folders needs 20,000 calls waiting at once.
The call stack is the memory where the runtime keeps every function call that has not returned yet. A stack frame is one call’s entry there: its arguments, its local variables and where to return. The call stack has a fixed size, and the RangeError above is what you get when the next frame does not fit.
So maxDepth needs one frame per level of the current path, which is O(h) memory for a tree of height h. On the wide tree of 100,000 folders, h is 10. On the chain, h is n.
Figure 2 shows the calls waiting on the call stack while maxDepth walks Figure 1’s tree, as trace-demo.ts prints it.
step calls waiting, bottom on the left
call home home
call docs home > docs
call tax home > docs > tax
tax returns 1 home > docs
call old home > docs > old
old returns 1 home > docs
docs returns 2 home
call photos home > photos
call 2024 home > photos > 2024
2024 returns 1 home > photos
photos returns 2 home
home returns 3 (empty)
Figure 2: the call stack holds one frame for every folder on the current path, so its size follows the depth, not the number of folders.
This walk goes as deep as it can down the first child before it looks at the next child. That order is called depth-first search (DFS). Recursion is the shortest way to write it, and its limit is the call stack.
Rule: A recursive walk needs one stack frame per level, so it fails on any input whose depth you don’t control.
Depth first with your own stack
A frame remembers which folder a call is on and how deep it is. You can keep that same information in an array instead. Arrays live on the heap, the large memory area where JavaScript keeps objects, and the heap has room for millions of entries.
Here is the depth-first walk with an explicit stack, from opening-fast.ts. The file also holds a breadth-first walk for the next section, and the benchmark.
// excerpt from opening-fast.ts
// Depth first with a stack of [folder, depth] pairs. O(n) time. The stack is an array on the heap,
// so a deep tree only costs memory: O(n) in the worst case.
export function maxDepthStack(root: Folder): number {
let deepest = 0;
const stack: [Folder, number][] = [[root, 1]];
while (stack.length > 0) {
const [folder, depth] = stack.pop()!;
if (depth > deepest) deepest = depth;
for (const child of folder.children) stack.push([child, depth + 1]);
}
return deepest;
}
maxDepthStack keeps [folder, depth] pairs on a stack. Each step pops one pair, updates deepest, and pushes a pair for every child, one level deeper. Figure 3 traces it on Figure 1’s tree, as trace-demo.ts prints it.
step stack of [folder depth], top on the right deepest
start [home 1] 0
pop home 1 [docs 2] [photos 2] 1
pop photos 2 [docs 2] [2024 3] 2
pop 2024 3 [docs 2] 3
pop docs 2 [tax 3] [old 3] 3
pop old 3 [tax 3] 3
pop tax 3 (empty) 3
Figure 3: each folder is pushed once and popped once, and the pair carries its depth, so no call has to wait for another.
The stack pops the last child pushed, so this walk visits photos before docs. For the height, the order doesn’t matter. A later section shows how to get the recursive order back.
Every folder is pushed once and popped once, so maxDepthStack is O(n) time. The stack holds the waiting children of every folder on the current path. That’s one item per level on a chain, and O(n) in the worst case, a root with n − 1 children.
Pause and predict. The recursive version makes a function call per folder. The stack version makes none, but it allocates a two-item array per folder. Which one is faster on the wide tree?
Here are the depth-first tables from what node opening-fast.ts printed:
recursive maxDepth, wide tree
n median ms x prev
250,000 4.52
500,000 8.55 1.9
1,000,000 15.73 1.8
maxDepthStack, wide tree
n median ms x prev
250,000 11.91
500,000 14.24 1.2
1,000,000 30.08 2.1
maxDepthStack, chain
n median ms x prev
250,000 10.27
500,000 33.97 3.3
1,000,000 56.11 1.7
Both grew about 2 times from 500,000 to 1,000,000 folders, as O(n) predicts. The smaller sizes jumped around between runs. In five more runs, the 1,000,000 row stayed close: recursion took 14.9 to 16.0 ms, and the stack of pairs 26.8 to 31.6 ms.
So the explicit stack is not faster than recursion. With a new [folder, depth] array per folder, it was about twice as slow.
What it buys is depth. On a chain of 1,000,000 folders, about 100 times deeper than the recursion could go, maxDepthStack returned the right answer, 1,000,000.
Rule: When the depth comes from input you don’t control, keep your own stack in an array.
Breadth first, one level at a time
Some questions are about levels, not paths. How many folders sit at each depth? Which matching folder is closest to the root? A depth-first walk mixes the levels, as Figure 3 shows.
Breadth-first search (BFS) visits the nodes in order of depth, one level at a time: the root, then all nodes at depth 2, then all at depth 3.
A queue gives that order. Take the front folder and add its children at the back, and the children wait behind every folder of the current level. maxDepthLevels uses Module 5’s Deque as the queue, because shift() on a large array is O(n).
// excerpt from opening-fast.ts
// Breadth first, one level at a time, with Module 5's Deque as the queue.
// O(n) time; O(w) memory, where w is the number of folders on the widest level.
export function maxDepthLevels(root: Folder): number {
const queue = new Deque<Folder>();
queue.push(root);
let depth = 0;
while (queue.size > 0) {
depth++;
// Here the queue holds exactly one level: take that many folders and queue their children.
for (let left = queue.size; left > 0; left--) {
const folder = queue.shift()!;
for (const child of folder.children) queue.push(child);
}
}
return depth;
}
At the start of each pass of the outer loop, the queue holds exactly one level. The inner loop takes queue.size folders, no more, and every child it adds belongs to the next level. Figure 4 traces it, as trace-demo.ts prints it.
depth folders taken from the front queue after (front on the left)
1 home docs, photos
2 docs, photos tax, old, 2024
3 tax, old, 2024 (empty)
Figure 4: the queue holds one whole level at the start of each pass, so counting the passes counts the levels.
Every folder enters and leaves the queue once, so maxDepthLevels is O(n) time. The queue holds at most the rest of the current level and the start of the next. So its memory is O(w), where w is the number of folders on the widest level.
If both walks are O(n), why pick one over the other?
Because they use memory differently. On the wide tree of 1,000,000 folders, the widest level has 650,475 folders, while maxDepthStack never holds more than 29 pairs (widths.ts counts both). On the chain, it’s the other way round: w is 1.
These are the breadth-first tables from the same run of node opening-fast.ts:
maxDepthLevels, wide tree
n median ms x prev
250,000 22.76
500,000 10.47 0.5
1,000,000 23.81 2.3
maxDepthLevels, chain
n median ms x prev
250,000 10.17
500,000 19.05 1.9
1,000,000 37.69 2.0
On the wide tree, it took 23.81 ms at 1,000,000 folders, close to the stack of pairs. On the chain, it grew about 2 times per doubling and returned 1,000,000 for the deepest chain.
Rule: For questions about levels, or about the match closest to the root, walk breadth first with a queue and take one level’s count of items per pass.
A binary search tree: sorted keys with fast inserts
Trees also hold data you build on purpose. Suppose you keep a set of prices that changes all day, and you need two things: “is this price in the set?” and “all prices in order”.
A Set answers the first in O(1) on average, but it keeps its items in insertion order, not sorted order. A sorted array has the order, but inserting into it with splice moves every later item, O(n) per insert.
A binary tree is a tree where every node has at most two children, called left and right. A subtree is a node together with everything below it. A binary search tree (BST) is a binary tree where, at every node, the keys in the left subtree are smaller and the keys in the right subtree are larger.
That rule tells a search which way to go at every node. Here are the insert and the lookup from bst.ts:
// excerpt from bst.ts
export type TreeNode = { key: number; left: TreeNode | null; right: TreeNode | null };
// Adds `key` and returns the root. O(h): it walks one path down from the root.
// A loop, not recursion, so a tall tree cannot overflow the call stack.
export function insert(root: TreeNode | null, key: number): TreeNode {
const node: TreeNode = { key, left: null, right: null };
if (root === null) return node;
let cur = root;
while (true) {
if (key === cur.key) return root; // no duplicates
if (key < cur.key) {
if (cur.left === null) {
cur.left = node;
return root;
}
cur = cur.left;
} else {
if (cur.right === null) {
cur.right = node;
return root;
}
cur = cur.right;
}
}
}
// O(h): one comparison per level.
export function has(root: TreeNode | null, key: number): boolean {
let cur = root;
while (cur !== null) {
if (key === cur.key) return true;
cur = key < cur.key ? cur.left : cur.right;
}
return false;
}
insert and has walk down one path. At each node, they go left for a smaller key and right for a larger one, until they find the key or fall off the tree. The full file also has these helpers:
inOrder, which the next section explainsheight, which counts levels breadth first likemaxDepthLevelsbuild, which inserts a list of keysshuffled, which returns 0 to n − 1 in random order
node bst.ts builds a small tree and prints:
inOrder: 10 20 30 40 50 60 70
has(30): true has(35): false height: 3
height with keys 10, 20, 30, 40 in order: 4
Figure 5 shows the tree that build([40, 20, 60, 10, 30, 50, 70]) makes, and the path that has(30) takes.
[40] has(30): 30 < 40, go left
/ \
[20] [60] 30 > 20, go right
/ \ / \
[10] [30] [50] [70] 30 = 30, found
height 3, 7 keys
Figure 5: every comparison discards one whole subtree, so a search visits one node per level.
Both functions do one comparison per level, so they are O(h) for a tree of height h. The question is how large h gets.
Sorted keys make the tree tall
When the keys arrive in random order, the tree stays bushy. When they arrive sorted, every new key is larger than all the others, so it goes right at every node. Figure 6 shows the keys 10, 20, 30 and 40 inserted in order.
[10]
\
[20]
\
[30]
\
[40]
height 4, 4 keys
Figure 6: sorted keys always go right, so the tree becomes a chain and every operation walks all of it.
Pause and predict. bst-bench.ts builds trees of 5,000, 10,000 and 20,000 keys, once from shuffled keys and once from sorted keys. How much longer does each build take per doubling?
// Height and build time of a plain BST, with shuffled keys and with sorted keys: node bst-bench.ts
import { bench } from "./bench.ts";
import { build, height, shuffled } from "./bst.ts";
const sorted = (n: number) => Array.from({ length: n }, (_, i) => i);
for (const n of [1_000, 10_000, 100_000]) {
const tall = n <= 10_000 ? height(build(sorted(n))) : "(not built)";
console.log(`n = ${n}: height ${height(build(shuffled(n)))} with shuffled keys, ${tall} with sorted keys, log2(n) = ${Math.log2(n).toFixed(1)}`);
}
bench("build from shuffled keys", [5_000, 10_000, 20_000], shuffled, build);
bench("build from sorted keys", [5_000, 10_000, 20_000], sorted, build);
Run node bst-bench.ts:
n = 1000: height 22 with shuffled keys, 1000 with sorted keys, log2(n) = 10.0
n = 10000: height 34 with shuffled keys, 10000 with sorted keys, log2(n) = 13.3
n = 100000: height 42 with shuffled keys, (not built) with sorted keys, log2(n) = 16.6
build from shuffled keys
n median ms x prev
5,000 0.31
10,000 1.08 3.4
20,000 2.49 2.3
build from sorted keys
n median ms x prev
5,000 21.12
10,000 89.34 4.2
20,000 388.08 4.3
With sorted keys, the height equals n. The i-th insert walks i nodes, so building n keys takes about n²/2 steps, O(n²). The build grew 4.2 and 4.3 times per doubling, and 20,000 keys took 388.08 ms.
With shuffled keys, the height was 22, 34 and 42, about 2 to 3 times log₂(n). For keys in random order, a search takes about 1.39 log₂(n) comparisons on average (Sedgewick and Wayne, section 3.2). So a build is O(n log n) on average, and 20,000 keys took 2.49 ms.
Times that small are too noisy for the ratios to mean much. Figure 7 draws both builds.
median ms to build a BST (each # is about 8.6 ms)
n = 5,000 sorted ## 21.12
shuffled | 0.31
n = 10,000 sorted ########## 89.34
shuffled | 1.08
n = 20,000 sorted ############################################# 388.08
shuffled | 2.49
Figure 7: sorted keys turn the tree into a chain and the build into O(n²), while shuffled keys keep it O(n log n).
Sorted input is common: ids, timestamps and log lines usually arrive in order. That’s why a plain BST is rarely the right structure in production code.
A balanced tree is a binary search tree that reshapes itself on insert and delete, so its height stays O(log n) for any order of keys. AVL trees and red-black trees are the two classic designs. How they rebalance is outside this course.
Rule: A binary search tree costs O(h) per operation, and h is n for sorted input. Use one only with random insert order or a balanced design.
Keys in sorted order: the in-order walk
The BST rule puts every smaller key on the left and every larger key on the right. So if you list a node’s left subtree, then the node, then its right subtree, the keys come out sorted.
An in-order walk visits a binary tree’s left subtree, then the node, then the right subtree. Two other orders have names. A pre-order walk visits a node before its children, as maxDepthStack does. A post-order walk visits the children before the node.
The recursive version takes a few lines. This excerpt shows the idea, but it fails on a tall tree, as the opening did:
// excerpt: in-order walk with recursion
if (node === null) return;
walk(node.left);
out.push(node.key);
walk(node.right);
inOrder in bst.ts does the same with an explicit stack:
// excerpt from bst.ts
// The keys in increasing order: the left subtree, then the node, then the right subtree.
// In-order walk with an explicit stack: O(n) time, O(h) memory.
export function inOrder(root: TreeNode | null): number[] {
const out: number[] = [];
const stack: TreeNode[] = []; // nodes whose left subtree is being walked
let cur = root;
while (cur !== null || stack.length > 0) {
while (cur !== null) {
stack.push(cur); // go left as far as possible
cur = cur.left;
}
const node = stack.pop()!; // its left subtree is done
out.push(node.key);
cur = node.right;
}
return out;
}
The stack holds the nodes whose left subtree is still being walked. Go left as far as you can, pushing each node. Then pop one, output its key, and walk its right subtree the same way. Figure 8 traces inOrder on Figure 5’s tree, as trace-demo.ts prints it.
nodes pushed pop stack after (top on the right) output so far
40, 20, 10 10 [40, 20] 10
- 20 [40] 10 20
30 30 [40] 10 20 30
- 40 [] 10 20 30 40
60, 50 50 [60] 10 20 30 40 50
- 60 [] 10 20 30 40 50 60
70 70 [] 10 20 30 40 50 60 70
Figure 8: a node is popped only after its whole left subtree, and its right subtree comes next, so the keys come out in increasing order.
Every node is pushed once and popped once, so inOrder is O(n) time. The stack holds at most one node per level of the current path, so its memory is O(h). The first line that node bst.ts printed shows the result: 10 20 30 40 50 60 70.
Rule: An in-order walk of a binary search tree lists its keys in sorted order, in O(n) time.
Three more shapes of a tree walk
The walks above come in a few more shapes. Each has a sign in the problem that points to it.
variations.ts holds all three. Its demo tree has two folders called tax, one at depth 4 under docs/old and one at depth 2. node variations.ts prints:
namesInOrder: home docs old tax tax photos 2024
folderTotals: tax 5, old 9, docs 11, tax 3, 2024 7, photos 13, home 28
nearestPath(home, 'tax'): home/tax
Visit in the recursive order
maxDepthStack visited photos before docs, because the stack pops the last child pushed. namesInOrder pushes the children in reverse, so the first child is on top and is popped first:
// excerpt from variations.ts
for (let i = folder.children.length - 1; i >= 0; i--) stack.push(folder.children[i]);
The output is the pre-order that the recursive walk would give. The sign is that the order matters, as in “list the folders as a file browser would show them”. When you only need a total or a maximum, the plain loop is enough.
Results that need the children first
A folder’s total size is its own size plus the totals of all its subfolders. So you need the children’s totals first, which is a post-order walk. Recursion does it naturally, but it hits the limit on deep trees.
folderTotals uses two passes instead:
- A stack walk lists every folder. In that list, every parent comes before its children.
- A loop walks the list backward, so it reaches every child before its parent, and adds the children’s totals to the parent’s size.
In the output, old gets 9 (4 + 5) before docs gets 11 (2 + 9). The sign is a value for each node that depends on everything inside it, such as total sizes or file counts. It costs O(n) time, plus O(n) memory for the list and a Map of totals.
The nearest match
nearestPath walks breadth first, so the first match it finds is on the highest level that has one. For tax, it returns home/tax at depth 2, not the deeper home/docs/old/tax that a depth-first walk reaches first.
To return the path and not only the folder, it keeps a Map from each folder to its parent:
// excerpt from variations.ts
if (folder.name === name) {
const path: string[] = [];
for (let f: Folder | null = folder; f !== null; f = parent.get(f)!) path.push(f.name);
return path.reverse();
}
for (const child of folder.children) {
parent.set(child, folder);
queue.push(child);
}
When it finds the match, it follows the parents up to the root and reverses the names. The sign is “closest to the root” or “fewest steps”. Module 7 uses the same idea for shortest paths in a graph.
Underneath: how deep recursion can go in Node.js
The facts in this section hold as of V8 14.6.202.34, the JavaScript engine in Node.js 26.13.1. node --v8-options lists the stack size, --stack-size, with a default of 984 KB.
So the limit is in bytes, not in calls. stack-depth.ts (shown in “Going deeper”) counts how many calls fit before the RangeError:
- A function with no arguments and no locals fit 12,442 frames, about 81 bytes each.
- A function with 8 arguments and 6 locals fit only 3,887 frames, about 259 bytes each.
Why did the opening handle a chain of 10,000 but not 20,000?
Because the limit also moves over time. chain-limit.ts finds the deepest chain the opening’s maxDepth handles, before and after warm-up:
deepest chain, cold: 4882
deepest chain, after 20 runs on a wide tree: 10369
Run cold, maxDepth handled 4,882 folders. After 20 runs on a wide tree, the JIT compiler from Module 1 had compiled it into machine code, and it handled 10,369. In the opening, the benchmark ran first, so the compiled function handled the chain of 10,000. In other words, a recursive function can pass in a warm server and fail on a fresh start, on the same input.
Raising the limit
--stack-size changes how much stack V8 assumes it has. With node --stack-size=2000 stack-depth.ts, the small function fit 25,447 frames, about twice as many.
But the flag doesn’t change the stack the operating system gave the thread. On this Mac, ulimit -s reports 8,192 KB for the main thread. A value above that lets V8 run past the end of the real stack:
node --stack-size=50000 stack-depth.ts; echo "exit $?"
The process printed nothing and exited with code 139. That code means a segmentation fault, which is how the operating system stops a process that touches memory it was not given. A Node.js maintainer explained it in nodejs/node#16870 (2017): the flag “tells V8 what to assume for the usable stack size”.
Rewriting the recursion so that the call is the last thing the function does doesn’t help either. The ECMAScript specification says such a call should not grow the stack. But V8 doesn’t do that, as “Going deeper” shows. So in Node.js, use a loop with an explicit stack.
Underneath: which walk and which structure to use
This table compares the walks in this module for a tree of n nodes, height h and widest level w:
| Walk | Time | Extra memory | Choose it when |
|---|---|---|---|
| Recursion | O(n) | O(h) call stack, fails above about 5,000 to 12,000 levels | the depth is small and known, such as a balanced tree or a config file you wrote |
| Explicit stack | O(n) | O(n) worst case, on the heap | the depth comes from input |
Queue by level (Deque) |
O(n) | O(w) | the question is about levels or the nearest match |
A BST is one way to hold a sorted set, and JavaScript has no built-in one. Map and Set keep insertion order, not sorted order. Here are the usual choices:
| Structure | Insert | Lookup | Keys in order | Choose it when |
|---|---|---|---|---|
Set or Map |
O(1) average | O(1) average | sort, O(n log n) | you rarely need the order |
| Sorted array | O(n) | O(log n) with binary search (Module 9) | O(n), already sorted | the data changes rarely |
| Plain BST | O(h) | O(h) | O(n) in-order | the insert order is random |
| Balanced BST (a library) | O(log n) | O(log n) | O(n) in-order | inserts and ordered reads are both frequent |
Common mistakes
mistakes.ts writes five bugs that are easy to make with trees, and prints what each one returns. Run node mistakes.ts:
1. levels without a boundary: [["home","docs","photos","tax","old","2024"]]
2. depth of a single folder, counting edges: 0 (the module counts folders: 1)
3. is 5(3, 6(4)) a BST? true (want false: 4 < 5 sits on 5's right)
4. stack DFS order: home photos 2024 docs old tax (recursive order: home docs tax old photos 2024)
5. BFS with shift() on 100,000 folders: depth 10, 581 ms
5. BFS with Deque on 100,000 folders: depth 10, 8 ms
A level walk with no level boundary. levelsBad takes folders from the front and adds children at the back, so the order is right. But it never records where one level ends, so every folder lands in one list. Take queue.size items per pass, as maxDepthLevels does.
Counting edges in one place and folders in another. depthEdges counts the links on the path, so a single folder has depth 0. This module counts folders, so a single folder has depth 1. Pick one meaning, write it in a comment, and test a tree of one node.
Checking each node only against its children. 5(3, 6(4)) is a tree with root 5, children 3 and 6, and 4 as the left child of 6. So 4 is a valid left child of 6, but it sits in 5’s right subtree, where every key must be larger than 5. Check each node against the bounds set by all its ancestors, the nodes on the path from the root down to it. Exercise 4 asks you to write that check.
Pushing the children in order on an explicit stack. The stack pops the last child first, so the walk visits photos before docs. That’s fine for a height or a total. When the order matters, push the children in reverse, as namesInOrder does.
A breadth-first walk on an array with shift(). On 100,000 folders, the widest level has 65,536. Every shift() then moves all of them, as Module 5 showed, and the walk took 581 ms against 8 ms with the Deque.
The opening showed the sixth mistake: recursion on input whose depth you don’t control. Raising --stack-size is not the fix, because a value above the real stack crashes with no message.
Exercises
The exercises are in the module’s exercises folder, each with a test file, and the solutions are in solutions. Run all the tests with:
node --test "exercises/*.test.ts"
All 23 tests fail until you write the five answers. Each exercise ends with a test that a correct but naive answer fails. The slow folder holds such answers: the recursive ones throw RangeError on the deep tests, and the others fail a time limit.
Exercise 1: the total size of a folder (easy)
Write totalSize(root): the sum of size over the folder and every folder inside it. It must work on a chain 1,000,000 folders deep. Start from exercises/total-size.ts:
import type { Folder } from "../folders.ts";
// Exercise 1: the sum of `size` over the folder and every folder inside it.
// It must work on a chain 1,000,000 folders deep.
export function totalSize(root: Folder): number {
throw new Error("not implemented");
}
The tests check a small tree, one folder, a wide tree of 100,000 folders and a chain of 1,000,000.
Hint
Use the shape of maxDepthStack. Does a total need the depth, or the order of the children?
Solution
import type { Folder } from "../folders.ts";
// Exercise 1: the sum of `size` over the folder and every folder inside it.
// It must work on a chain 1,000,000 folders deep.
// Depth first with an explicit stack: O(n) time, O(n) memory in the worst case, no call stack limit.
export function totalSize(root: Folder): number {
let total = 0;
const stack: Folder[] = [root];
while (stack.length > 0) {
const folder = stack.pop()!;
total += folder.size;
for (const child of folder.children) stack.push(child);
}
return total;
}
Cost: O(n) time, because every folder is pushed once and popped once. O(n) memory in the worst case, for a root with n − 1 children. A sum doesn’t depend on the order, so the children can go on the stack in any order. The recursive answer in slow/ throws RangeError: Maximum call stack size exceeded on the chain.
Exercise 2: folder names by level (easy)
Write namesByLevel(root): one array of names per level, top level first, children in array order. For Figure 1’s tree, it returns [["home"], ["docs", "photos"], ["tax", "old", "2024"]]. Start from exercises/names-by-level.ts:
import type { Folder } from "../folders.ts";
// Exercise 2: the folder names on each level, top level first, children in array order.
// You may import the Deque from "../deque.ts".
export function namesByLevel(root: Folder): string[][] {
throw new Error("not implemented");
}
The tests check Figure 1’s tree, one folder, a chain 100,000 deep, and a wide tree of 200,000 folders in under 500 ms.
Hint
Use the loop of maxDepthLevels. Where do you start a new array of names, and where do you add it to the answer?
Solution
import { Deque } from "../deque.ts";
import type { Folder } from "../folders.ts";
// Exercise 2: the folder names on each level, top level first, children in array order.
// Breadth first by level with a Deque: O(n) time, O(w) memory for the queue (w = widest level),
// plus O(n) for the answer.
export function namesByLevel(root: Folder): string[][] {
const out: string[][] = [];
const queue = new Deque<Folder>();
queue.push(root);
while (queue.size > 0) {
const names: string[] = [];
for (let left = queue.size; left > 0; left--) {
const folder = queue.shift()!;
names.push(folder.name);
for (const child of folder.children) queue.push(child);
}
out.push(names);
}
return out;
}
Cost: O(n) time, because every folder enters and leaves the queue once. The queue needs O(w) memory for a widest level of w folders, and the answer holds all n names. With an array and shift(), the wide tree’s levels pass the cliff from Module 5, and the last test took 2,768 ms.
Exercise 3: the path to a folder (medium)
Write findPath(root, name): the names from the root down to the first folder called name, or null. “First” means first in depth-first order, with children visited in array order, as a recursive walk would visit them. It must work on a chain 1,000,000 folders deep. Start from exercises/find-path.ts:
import type { Folder } from "../folders.ts";
// Exercise 3: the folder names from the root to the first folder called `name`, or null.
// "First" means first in depth-first order, visiting children in array order.
// It must work on a chain 1,000,000 folders deep.
export function findPath(root: Folder, name: string): string[] | null {
throw new Error("not implemented");
}
The tests check a nested folder, a name that appears twice at different depths, the root itself, a missing name, and the chain.
Hint
Combine two variations: the visiting order of namesInOrder, and the parent Map of nearestPath. Why is a breadth-first walk wrong here?
Solution
import type { Folder } from "../folders.ts";
// Exercise 3: the folder names from the root to the first folder called `name`, or null.
// "First" means first in depth-first order, visiting children in array order.
// It must work on a chain 1,000,000 folders deep.
// An explicit stack with the children pushed in reverse, and a map from each folder to its parent:
// O(n) time, O(n) memory.
export function findPath(root: Folder, name: string): string[] | null {
const parent = new Map<Folder, Folder | null>([[root, null]]);
const stack: Folder[] = [root];
while (stack.length > 0) {
const folder = stack.pop()!;
if (folder.name === name) {
const path: string[] = [];
for (let f: Folder | null = folder; f !== null; f = parent.get(f)!) path.push(f.name);
return path.reverse();
}
for (let i = folder.children.length - 1; i >= 0; i--) {
parent.set(folder.children[i], folder);
stack.push(folder.children[i]);
}
}
return null;
}
Cost: O(n) time, because every folder is pushed once and popped once, and rebuilding the path is O(depth). O(n) memory for the parent map.
A breadth-first walk returns the match closest to the root, so it fails the second test. That test wants home/docs/old/tax, which comes before the shallower home/tax in depth-first order. The recursive answer in slow/ throws RangeError on the chain.
Exercise 4: is it a binary search tree? (medium)
Write isBst(root): true when the tree follows the BST rule with no duplicate keys. Every key in a node’s left subtree must be smaller than the node’s key, and every key in its right subtree larger. Start from exercises/is-bst.ts:
import type { TreeNode } from "../bst.ts";
// Exercise 4: true when the tree is a binary search tree with no duplicate keys:
// every key in a node's left subtree is smaller than the node's key, every key in its right subtree larger.
export function isBst(root: TreeNode | null): boolean {
throw new Error("not implemented");
}
The tests check valid trees, a child on the wrong side, the grandchild case from the common mistakes, a duplicate, and a tall tree of 30,000 sorted keys.
Hint
Each node must lie between a lower and an upper bound that its ancestors set. Going left, the node’s key becomes the new upper bound; going right, the new lower bound. Carry the bounds on the stack, as maxDepthStack carries the depth.
Solution
import type { TreeNode } from "../bst.ts";
// Exercise 4: true when the tree is a binary search tree with no duplicate keys:
// every key in a node's left subtree is smaller than the node's key, every key in its right subtree larger.
// Each node carries the bounds its ancestors set, on an explicit stack: O(n) time,
// O(h) memory (at most one waiting sibling per level of the current path).
export function isBst(root: TreeNode | null): boolean {
const stack: [TreeNode | null, number, number][] = [[root, -Infinity, Infinity]];
while (stack.length > 0) {
const [node, low, high] = stack.pop()!;
if (node === null) continue;
if (node.key <= low || node.key >= high) return false;
stack.push([node.left, low, node.key], [node.right, node.key, high]);
}
return true;
}
Cost: O(n) time, because every node is checked once. O(h) memory, because the stack holds at most one waiting sibling per level of the current path, plus the two children of the last node. The bounds start at -Infinity and Infinity, so the root needs no special case. The recursive answer in slow/ throws RangeError on the tall tree.
Exercise 5: keys in a range (harder)
Write keysInRange(root, low, high): the keys k with low <= k <= high, in increasing order. Don’t visit subtrees that cannot hold a key in the range. Start from exercises/keys-in-range.ts:
import type { TreeNode } from "../bst.ts";
// Exercise 5: the keys k with low <= k <= high, in increasing order.
// Do not visit subtrees that cannot hold a key in the range.
export function keysInRange(root: TreeNode | null, low: number, high: number): number[] {
throw new Error("not implemented");
}
The tests check Figure 5’s tree, empty trees and ranges, a range above every key, a tall tree, and 500 narrow ranges on 100,000 shuffled keys in under 200 ms.
Hint
Start from inOrder in bst.ts. When a node’s key is below low, which part of the tree below it can you skip? When a popped key is above high, what do you know about every key after it?
Solution
import type { TreeNode } from "../bst.ts";
// Exercise 5: the keys k with low <= k <= high, in increasing order.
// Do not visit subtrees that cannot hold a key in the range.
// The in-order walk from the reading, with two cuts: skip a node and its left subtree when the
// node is below `low`, and stop at the first key above `high`. O(h + m) time for m keys, O(h) memory.
export function keysInRange(root: TreeNode | null, low: number, high: number): number[] {
const out: number[] = [];
const stack: TreeNode[] = [];
let cur = root;
while (cur !== null || stack.length > 0) {
while (cur !== null) {
if (cur.key < low) cur = cur.right; // cur and its whole left subtree are too small
else {
stack.push(cur);
cur = cur.left;
}
}
if (stack.length === 0) break;
const node = stack.pop()!;
if (node.key > high) break; // every later key is larger still
out.push(node.key);
cur = node.right;
}
return out;
}
Cost: O(h + m) time for m keys in the range. The walk goes down one path to reach low, then visits each key in the range and the nodes on the paths between them. O(h) memory for the stack.
The stack.length === 0 check matters when every key is below low. Then the inner loop goes right until it falls off the tree, and nothing is left to pop. Walking the whole tree and filtering is O(n) per query, and in slow/ it took 1,299 ms on the last test.
Going deeper
You can skip this section. It covers details the main path left out.
The odd spaces in the error
The opening’s error shows maxDepth(folder ) with extra spaces. Those spaces were the type annotations: Node.js replaces types with spaces when it strips them, so line and column numbers stay the same (Node.js docs on type stripping). The error also shows only 10 at maxDepth lines, because Error.stackTraceLimit is 10 by default (Node.js errors docs).
An explicit stack as fast as recursion
opening-fast.ts also has maxDepthTwoStacks. It is the same walk with two parallel stacks, one of folders and one of depths, so it allocates no pair per folder:
// excerpt from opening-fast.ts
// The same walk with two parallel stacks, so no [folder, depth] array is allocated per folder.
export function maxDepthTwoStacks(root: Folder): number {
let deepest = 0;
const folders: Folder[] = [root];
const depths: number[] = [1];
while (folders.length > 0) {
const folder = folders.pop()!;
const depth = depths.pop()!;
if (depth > deepest) deepest = depth;
for (const child of folder.children) {
folders.push(child);
depths.push(depth + 1);
}
}
return deepest;
}
Its table from the same run:
maxDepthTwoStacks, wide tree
n median ms x prev
250,000 3.99
500,000 10.47 2.6
1,000,000 14.07 1.3
In the five more runs, it took 14.1 to 16.1 ms at 1,000,000 folders, so it matched recursion. It also returned 1,000,000 for the chain of 1,000,000. Use it where speed matters; the pair version is easier to read.
Measuring the stack limit
stack-depth.ts in the course repository produced the frame counts in “Underneath”. It counts the calls that fit before the RangeError for four functions:
small(), with no arguments and no localsbig(), with 8 arguments and 6 localssum(n), which returnssum(n - 1) + 1, run once cold and once after 200,000 short callscountDown(n), which returnscountDown(n - 1), a tail call (explained below)
node stack-depth.ts printed:
small(), first call 12442 frames RangeError: Maximum call stack size exceeded
small(), second call 12442 frames RangeError: Maximum call stack size exceeded
big(8 params, 6 locals), first call 3887 frames RangeError: Maximum call stack size exceeded
sum(), cold 10367 frames RangeError: Maximum call stack size exceeded
sum(), after 200,000 shallow calls 13823 frames RangeError: Maximum call stack size exceeded
countDown(1e6), a tail call 10367 frames RangeError: Maximum call stack size exceeded
sum reached 10,367 frames on its first call and 13,823 after 200,000 short calls, the same warm-up effect as chain-limit.ts. With --stack-size=500, small() fit 6,247 frames.
Tail calls
A tail call is a call whose result the caller returns directly, as in return countDown(n - 1). The caller has nothing left to do, so its frame could be dropped before the call. The ECMAScript specification requires this in strict code since ES2015 (ECMAScript, Tail Position Calls).
ES modules are always strict. But countDown still overflowed at 10,367 frames, the same as sum on its first call. V8 implemented tail calls in 2016 and did not ship them, because dropped frames make stack traces harder to read (V8 blog, 2016). The flags were later removed.
Safari’s engine ships them (WebKit blog, 2016). A proposal for tail calls with explicit syntax is listed as abandoned (TC39 inactive proposals).
A bigger stack in a worker thread
A worker thread gets its own stack, sized by resourceLimits.stackSizeMb, which defaults to 4 (Node.js worker threads docs). In worker-stack.ts, maxDepth on a chain of 100,000 failed in a worker with 4 MB and returned 100,000 with 64 MB. That costs a thread, and you must build the tree inside the worker or copy it there. An explicit stack costs neither.
What changed recently
On Node.js 22.17 (V8 12.4), the same laptop fit 12,104 frames of small() and 10,086 of sum on its first call, a little fewer than Node.js 26. The default size is 984 KB in both.
On 64-bit ARM, such as Apple silicon Macs, the default changed. V8 12.4 used 864 KB on ARM and ARM64. In February 2025, V8 started measuring the limit from the start of the stack, and ARM64 moved to 984 KB (commit c1b30364b1, first in V8 13.5).
So Node.js 24 and later allow more depth on ARM64 than Node.js 22. This comes from the source (globals.h at 14.6.202.34), not from a run on an ARM64 machine.
How short a balanced tree stays
A red-black tree’s height is at most 2 log₂(n) (Sedgewick and Wayne, section 3.3).
Cheat sheet
Figure 9 sums up the module: which walk fits which sign in a problem.
sign in the problem walk memory
any order is fine, depth from input stack of [node, state] O(n)
"in the order a file browser shows" stack, children reversed O(n)
a value from everything inside a node parent-first list, back O(n)
per level, "closest to the root" queue by level (Deque) O(w)
sorted keys with inserts, random order binary search tree O(n)
keys in order, or in a range in-order walk O(h)
Figure 9: a stack goes deep first and a queue goes level by level, and a binary search tree is only as fast as it is short.
- Recursion: one stack frame per level; the 984 KB stack fit about 5,000 to 12,000 levels, fewer before warm-up.
- Explicit stack:
[node, state]pairs in an array handle any depth, at about the speed of recursion or half of it. - Breadth first: a
Deque, andqueue.sizeitems per pass is one level. O(n) time, O(w) memory. - BST: left smaller, right larger; insert and lookup are O(h). h is about 2 to 3 log₂(n) for random order and n for sorted order.
- In-order: left, node, right; a BST’s keys come out sorted. Prune with
lowandhighfor a range. - Next: Module 7 walks graphs, where a node can be reached by more than one path, so the walk needs a set of visited nodes.
Sources
- V8 source at 14.6.202.34, the version in Node.js 26.13.1:
globals.h(V8_DEFAULT_STACK_SIZE_KB),flag-definitions.h(stack_size); commit c1b30364b1 (2025, the ARM64 default). - V8 blog: ES2015, ES2016, and beyond (2016, proper tail calls).
- Node.js 26.13.1 docs:
Error.stackTraceLimit, Type stripping,resourceLimitsin worker threads; nodejs/node#16870 on--stack-size. - ECMAScript specification: Tail Position Calls; TC39 inactive proposals.
- WebKit blog: ECMAScript 6 Proper Tail Calls in WebKit (2016).
- Robert Sedgewick and Kevin Wayne, Algorithms, 4th edition: 3.2 Binary Search Trees, 3.3 Balanced Search Trees.