Here is a first answer to 543. Diameter of Binary Tree: the longest path turns at some node, so try every node as the turning point, add the heights of its two subtrees, and keep the best.
// Height in nodes: 0 for an empty tree. O(size of the subtree).
function height(node: TreeNode | null): number {
if (node === null) return 0;
return 1 + Math.max(height(node.left), height(node.right));
}
// O(n·h) time, O(n²) on a chain: every node recomputes the height of both subtrees from scratch.
// O(h) memory: the call stack.
export function diameterRecomputingHeights(root: TreeNode | null): number {
if (root === null) return 0;
const throughRoot = height(root.left) + height(root.right);
return Math.max(throughRoot, diameterRecomputingHeights(root.left), diameterRecomputingHeights(root.right));
}
LeetCode allows 10⁴ nodes, and nothing stops them from forming one long chain. Then every node measures everything below it again, about 5 × 10⁷ steps, inside the budget from Module 1, and with a larger call stack it finished in 607.0 ms. But a fresh Node.js process doesn’t get that far. On that chain it threw RangeError: Maximum call stack size exceeded. A version that computes each height once, with no recursion, returned 9,999 in 1.6 ms.
This module works eight problems on binary trees, where the natural answer is a recursive function that solves the problem for both children and then for the node. Each one follows the nine steps from Module 1. Five of them end with the same follow-up: what if the tree is one long chain, deeper than Node.js’s call stack allows?
After this module, you can:
- write a recursive tree walk that combines the answers of a node’s two children, and state its O(h) memory
- find an answer that turns at some node (the longest path, the largest path sum) in one pass, with each node returning one number to its parent
- walk a tree level by level with one array per level
- use a binary search tree’s order to validate it, find its k-th smallest value, and rebuild a tree from two listings
- tell when the limits allow a chain deeper than Node.js’s call stack, and move the recursion onto an explicit stack
The code for this module is in module-07/ of the course repository, and node --test "module-07/**/*.test.ts" from its root runs every test. atlimit.ts in the module folder calls each solution once on the longest chain its problem allows, so its times are rough, and yours will differ. Every number on this page comes from Node.js 24.22.1 on an Apple M2 laptop with macOS.
The pattern: answer for the children, then for the node
A binary tree is a set of nodes where each node has at most two children, a left one and a right one. The top node is the root, a node with no children is a leaf, and a node with everything below it forms a subtree. DSA Module 6 teaches trees. LeetCode gives every tree problem the same node class, and the lab defines it in shared/tree-node.ts:
// LeetCode's TreeNode, with the same fields and constructor as its TypeScript template.
export class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
}
LeetCode declares TreeNode for you, so paste each solution without the lab file’s import line.
LeetCode writes a tree as an array, level by level from the top, left to right, with null for a missing child. So [1, 2, 3, null, 4] is a root 1 with children 2 and 3, and 2 has only a right child, 4. This page writes trees the same way.
Most tree answers have one shape. The answer for a node comes from the answers for its left and right subtrees, and an empty subtree has a fixed answer, such as 0. Written as a recursive function, that’s three or four lines.
Signs that point to this pattern:
- the input is a
TreeNode - a question about a whole subtree: its height, its longest path, its largest sum, whether its values are in order
- “level by level” or “left to right within a level”
- a binary search tree, or two listings of the same tree’s values
The cost is the call stack. A recursive walk keeps one call waiting for every node on the current path, so its memory grows with the height of the tree. When the limits allow a chain of 10⁴ nodes, that’s 10⁴ calls waiting at once, and a fresh Node.js process can’t hold that many for most of this module’s functions.
Rule: On a tree, compute each node’s answer from its children’s answers. When the tree can be a long chain, keep the path on an explicit stack, not the call stack.
226. Invert Binary Tree
226. Invert Binary Tree is rated Easy. You get the root of a binary tree, which may be empty. Turn the tree into its mirror image, so that at every node the left and right children trade places, and return the root.
0 ≤ n ≤ 100nodes-100 ≤ Node.val ≤ 100
The signature is function invertTree(root: TreeNode | null): TreeNode | null. Try it on LeetCode first.
Hint
If both subtrees were already mirrored, what would be left to do at the root?
Interviewer: Mirror this tree, and return its root.
Candidate: So the children trade places at every node, not only at the root. Can the tree be empty?
Interviewer: Yes.
Candidate: Then I return null. Should I change this tree, or build a new one?
Interviewer: Changing it is fine.
Candidate: How big can it be?
Interviewer: Up to 100 nodes.
The interviewer and the candidate are invented. The problems, limits and timings are real.
Candidate: Here’s my example and three edge cases.
tree expected
[1, 2, 3, 4, null, null, 5] [1, 3, 2, 5, null, null, 4]
[] [] empty: return null
[7] [7] one node, nothing to swap
a chain of 100 to the left the same chain, to the right
Candidate: Every node has to move, so no answer can beat O(n), and the obvious answer already reaches it. I mirror both subtrees, then swap them.
Some problems have no slow answer to start from. Say so in the interview, and give the reason. Every node must be touched, so O(n) is the floor.
// O(n) time: each node is swapped once. O(h) memory: one call frame per node on the current path.
function invertTree(root: TreeNode | null): TreeNode | null {
if (root === null) return null;
const invertedLeft = invertTree(root.left);
root.left = invertTree(root.right);
root.right = invertedLeft;
return root;
}
export { invertTree };
Candidate: I save the inverted left subtree first, because the next line overwrites root.left.
Interviewer: Trace your example.
Figure 1 shows the tree before and after, and the order in which the calls return.
before after
[1] [1]
/ \ / \
[2] [3] [3] [2]
/ \ / \
[4] [5] [5] [4]
call returns at that node
4 no children, nothing to swap
2 left = null, right = [4]
5 no children, nothing to swap
3 left = [5], right = null
1 left = [3], right = [2]
Figure 1: each call mirrors its subtrees before it swaps them, so a node’s swap moves subtrees that are already mirrored.
Candidate: For [], the first line returns null. For [7], both calls return null, and swapping two nulls changes nothing.
Interviewer: Final cost?
Candidate: O(n) time: each node is swapped once. O(h) memory, where h is the height: one call waits for each node on the current path. At 100 nodes, that’s at most 100 calls.
A tree’s height is the number of nodes on its longest path from the root down to a leaf. A balanced tree of n nodes has a height of about log₂ n; a tree where every node has one child has a height of n.
Interviewer: Can you do it without recursion?
The Candidate’s answer
Candidate: Yes. I keep the nodes still to visit in an array. I pop one, swap its children, and push them. The order doesn’t matter, because each swap changes only one node’s two links.
// O(n) time: each node is popped once. O(h) memory: the stack holds the path plus one waiting sibling per level,
// and it lives on the heap, so a deep tree cannot overflow the call stack.
export function invertTreeStack(root: TreeNode | null): TreeNode | null {
const stack: TreeNode[] = root ? [root] : [];
while (stack.length > 0) {
const node = stack.pop()!;
const left = node.left;
node.left = node.right;
node.right = left;
if (node.left) stack.push(node.left);
if (node.right) stack.push(node.right);
}
return root;
}
Candidate: It’s still O(n) time. At 100 nodes I’d write the recursive one, because it’s shorter and the depth is safe.
Interviewer: The caller still needs the original tree. What changes?
The Candidate’s answer
Candidate: I build a new TreeNode for every node, with the mirrored copies of its subtrees as children. It’s still O(n) time, and O(n) extra memory for the new nodes.
This version isn’t in the lab.
Interviewer: How would you check whether a tree is its own mirror?
The Candidate’s answer
Candidate: I walk the left and right subtrees at the same time, in opposite directions: the left child of one against the right child of the other. Every pair must hold equal values. That’s O(n) time.
That’s LeetCode’s 101. Symmetric Tree, which this course doesn’t cover. This version isn’t in the lab.
One mistake is common here. mistakes.ts in the module folder prints the wrong output of every mistake in this module that has one.
- Overwriting
root.leftbefore saving it.root.left = invertTree(root.right)followed byroot.right = invertTree(root.left)inverts the right subtree twice and hangs it on both sides. Our example returns[1, 3, 3, 5, 5, 5, 5]instead of[1, 3, 2, 5, null, null, 4]. Save the inverted left subtree in a variable first.
Lab folder: module-07/0226-invert-binary-tree/ in the course repository.
104. Maximum Depth of Binary Tree
104. Maximum Depth of Binary Tree is rated Easy. You get the root of a binary tree. Return how many nodes lie on its longest path from the root down to a leaf, which is the tree’s height. An empty tree has a depth of 0.
0 ≤ n ≤ 10^4nodes-100 ≤ Node.val ≤ 100
The signature is function maxDepth(root: TreeNode | null): number. Try it on LeetCode first.
Hint
A tree is one level taller than the taller of its two subtrees.
Interviewer: Return the maximum depth of this tree.
Candidate: Do you count nodes or edges? A single node could have a depth of 1 or 0.
Interviewer: Nodes. One node has a depth of 1.
Candidate: Then an empty tree has 0. How many nodes can there be?
Interviewer: Up to 10⁴.
Candidate: Can they all be in one line, each node with one child?
Interviewer: Yes, the limits allow that.
A tree where every node has at most one child is a chain. Its height equals its number of nodes, so it’s the deepest tree a given n allows.
Candidate: Here’s my example and three edge cases.
tree expected
[1, 2, 3, null, 4, null, null, 5] 4 the path 1, 2, 4, 5
[] 0 empty
[0] 1 one node counts as 1
a chain of 10^4 nodes 10000 the height is n
Candidate: The natural answer is recursive. An empty tree has a depth of 0, and any other tree is one more than its taller subtree.
// O(n) time: each node is visited once. O(h) memory: one call frame per node on the current path.
export function maxDepthRecursive(root: TreeNode | null): number {
if (root === null) return 0;
return 1 + Math.max(maxDepthRecursive(root.left), maxDepthRecursive(root.right));
}
This walk follows one branch all the way down before it comes back up to try the next. That order is a depth-first search (DFS), which DSA Module 6 also writes with an explicit stack.
Candidate: Each node is visited once, so it’s O(n) time, and there’s no repeated work to remove. The memory is O(h) waiting calls.
The lab names this function maxDepthRecursive. The version to paste into LeetCode is maxDepth, in the answer to the first follow-up below, because it also handles the longest chain the limits allow.
Interviewer: Trace your example.
Figure 2 shows the tree and the value each call returns. A call returns only after both of its children have.
[1] call returns
/ \ 5 1 + max(0, 0) = 1
[2] [3] 4 1 + max(1, 0) = 2
\ 2 1 + max(0, 2) = 3
[4] 3 1 + max(0, 0) = 1
/ 1 1 + max(3, 1) = 4
[5]
Figure 2: each call adds one level to the taller answer of its children, so the root returns the number of nodes on the longest path.
Candidate: For [], the first line returns 0. For [0], both calls return 0, and the root returns 1.
Interviewer: Final cost?
Candidate: O(n) time: one call per node. O(h) memory: one waiting call per node on the current path, which is n on a chain.
Interviewer: You said the tree can be a chain of 10⁴ nodes. Does your code handle it?
The Candidate’s answer
Candidate: Not safely. On a chain, maxDepthRecursive has 10⁴ calls waiting at the bottom, and Node.js limits how many calls can wait at once.
Module 4 explains the call stack: one frame for each call that hasn’t returned, in a space whose size V8 caps. In atlimit.ts, maxDepthRecursive threw RangeError: Maximum call stack size exceeded on a chain of 10⁴ nodes.
In a run of stack-depth.ts in the same folder, the longest chain it handled on a first call was 7,760 nodes. After 2,000 calls on small trees had let the JIT compiler optimize it, it handled 10⁴. So the same code can pass on a warm server and fail on a fresh start.
Candidate: So I count levels instead, with arrays on the heap. I keep the nodes of the current level, build the next level from their children, and count levels until one is empty.
Visiting a tree level by level from the top is a breadth-first search (BFS).
// O(n) time: each node enters one level once. O(w) memory: two levels at a time (w = widest level),
// with no recursion, so a 10^4-node chain is safe.
function maxDepth(root: TreeNode | null): number {
let depth = 0;
let level: TreeNode[] = root ? [root] : [];
while (level.length > 0) {
depth++;
const next: TreeNode[] = [];
for (const node of level) {
if (node.left) next.push(node.left);
if (node.right) next.push(node.right);
}
level = next;
}
return depth;
}
export { maxDepth };
Candidate: On my example, the levels are [1], [2, 3], [4] and [5], so the depth is 4. Every node is on exactly one level, so it’s O(n) time. Memory is O(w), the widest level: about n/2 nodes in a full tree, and one on a chain.
In atlimit.ts, maxDepth returned 10000 on the chain in 1.6 ms.
Interviewer: How would you find the minimum depth instead?
The Candidate’s answer
Candidate: With levels, I stop at the first level that holds a leaf. With recursion, I must not take the minimum with a missing child: a node with one child isn’t a leaf, so its depth comes from the child it has.
That’s LeetCode’s 111. Minimum Depth of Binary Tree, which this course doesn’t cover. This version isn’t in the lab.
Interviewer: How would you check that, at every node, the two subtrees’ heights differ by at most one?
The Candidate’s answer
Candidate: The same recursion returns the height, plus a flag that turns false as soon as two children’s heights differ by more than one. Each height is computed once, so it’s O(n).
That’s LeetCode’s 110. Balanced Binary Tree, which this course doesn’t cover. This version isn’t in the lab.
Two mistakes are common here:
- Counting edges instead of nodes. A version that returns 0 for a leaf gives
[1]a depth of0instead of 1. Return 0 only for an empty tree, and add 1 for every node. - Recursion on the chain.
maxDepthRecursivethrowsRangeError: Maximum call stack size exceededon a chain of 10⁴ nodes in a fresh process. Count levels with arrays instead.
Lab folder: module-07/0104-maximum-depth-of-binary-tree/ in the course repository.
543. Diameter of Binary Tree
543. Diameter of Binary Tree is rated Easy. You get the root of a binary tree. Return the number of edges on the longest path between any two of its nodes. The path may turn at any node, not only at the root.
1 ≤ n ≤ 10^4nodes-100 ≤ Node.val ≤ 100
The signature is function diameterOfBinaryTree(root: TreeNode | null): number. Try it on LeetCode first.
Hint
Every path has one highest node, where it turns. How long is the longest path that turns at a given node?
Interviewer: Find the diameter of this tree.
A tree’s diameter is the number of edges on its longest path between two nodes.
Candidate: Do I count edges or nodes on the path?
Interviewer: Edges.
Candidate: So one node gives 0, and two nodes give 1. Must the path go through the root?
Interviewer: No.
Candidate: Can the tree be empty?
Interviewer: No. It has 1 to 10⁴ nodes.
Candidate: Here’s my example and three edge cases.
tree expected
[1, 2, null, 4, 5, 6, null, null, 7] 4 6, 4, 2, 5, 7: it turns at 2
[1] 0 one node
[1, 2] 1 one edge
a chain of 10^4 nodes 9999
Figure 3 draws the example. The longest path through the root, 6, 4, 2, 1, has only 3 edges.
[1]
/
[2]
/ \
[4] [5]
/ \
[6] [7]
Figure 3: the longest path, 6 to 7, turns at node 2 and never reaches the root.
Candidate: The path turns at its highest node. From there it goes as far down the left subtree as it can, and as far down the right. A subtree of height h adds h edges, so the path has height(left) + height(right) edges.
Candidate: So the naive solution tries every node as the turning point, with a height function that walks the subtree.
The Candidate writes diameterRecomputingHeights, the function at the top of this page.
Pause and predict. On a chain of n nodes, about how many nodes do all the height calls visit together?
Candidate: At each node, height walks everything below it. On a chain that’s n − 1 nodes, then n − 2, and so on, about n²/2 in all. In general it’s O(n·h) time, and O(n log n) on a balanced tree. Memory is O(h) waiting calls.
Candidate: At 10⁴ nodes, n²/2 is 5 × 10⁷ steps, inside the budget.
So the naive answer isn’t too slow at this limit. atlimit.ts can run with a larger call stack, node --stack-size=7500 module-07/atlimit.ts, and there diameterRecomputingHeights took 607.0 ms on the chain of 10⁴. Without the flag, it threw RangeError first. The measurement at the end of this page shows its time growing four times per doubling on a chain, the O(n²) case.
Interviewer: What does it repeat?
Candidate: A node’s height is computed again for every node above it. The height of 6 is computed when 4, 2 and 1 are each tried as the turning point.
Candidate: But a node’s height is one more than the taller height of its children. So if every call returns its height to its parent, each height is computed once. On the way, each call also records left + right as a candidate for the diameter.
A walk that finishes both children before it handles the node is a post-order walk. It’s what lets each node use both of its children’s answers.
// O(n) time: one post-order pass returns each height once and checks the path through each node.
// O(h) memory: the call stack.
export function diameterRecursive(root: TreeNode | null): number {
let longest = 0;
function heightAndUpdate(node: TreeNode | null): number {
if (node === null) return 0;
const left = heightAndUpdate(node.left);
const right = heightAndUpdate(node.right);
longest = Math.max(longest, left + right); // edges on the longest path that turns at this node
return 1 + Math.max(left, right);
}
heightAndUpdate(root);
return longest;
}
Candidate: The function returns one number, the height, because that’s all the parent needs. The diameter goes into longest, outside it.
The lab names this function diameterRecursive. The version to paste into LeetCode is diameterOfBinaryTree, in the answer to the first follow-up below.
Interviewer: Trace your example.
Figure 4 lists the calls in the order they finish. left and right are the heights the two children returned.
node left right left + right longest returns
6 0 0 0 0 1
4 1 0 1 1 2
7 0 0 0 1 1
5 0 1 1 1 2
2 2 2 4 4 3
1 3 0 3 4 4
Figure 4: every height is computed once and handed up, and the best turn, 4 edges at node 2, stays in longest while the root returns later.
Candidate: For [1], both children return 0, so longest stays 0. For [1, 2], node 2 returns 1, and the root records 1 + 0 = 1.
Interviewer: Final cost?
Candidate: O(n) time: one call per node, with O(1) work in each. O(h) memory for the waiting calls.
Interviewer: The tree can be a chain of 10⁴ nodes. Does that change anything?
The Candidate’s answer
Candidate: Yes, the same as for 104: 10⁴ calls would wait at once. In atlimit.ts, diameterRecursive threw RangeError: Maximum call stack size exceeded on that chain. In the run of stack-depth.ts, it handled 7,759 nodes on a first call, and it still failed at 10⁴ after the warm-up.
Candidate: So I do the same post-order pass with my own stack. I look at the node on top: if a child isn’t finished, I push it and look again. When both children are finished, I pop the node and compute its height from theirs. A Map keeps the height of every finished node, with null mapped to 0.
// O(n) time: each node is pushed and popped once, children before parents. O(n) memory: the heights map;
// no recursion, so a 10^4-node chain is safe.
function diameterOfBinaryTree(root: TreeNode | null): number {
let longest = 0;
const heights = new Map<TreeNode | null, number>([[null, 0]]);
const stack: TreeNode[] = root ? [root] : [];
while (stack.length > 0) {
const node = stack[stack.length - 1];
if (node.left && !heights.has(node.left)) { stack.push(node.left); continue; }
if (node.right && !heights.has(node.right)) { stack.push(node.right); continue; }
stack.pop();
const left = heights.get(node.left)!;
const right = heights.get(node.right)!;
longest = Math.max(longest, left + right);
heights.set(node, 1 + Math.max(left, right));
}
return longest;
}
export { diameterOfBinaryTree };
Candidate: Each node is pushed once and popped once, so it’s O(n) time. The Map holds every height, O(n) memory, and the stack holds the current path, O(h). Both live on the heap.
In atlimit.ts, diameterOfBinaryTree returned 9999 on the chain of 10⁴ in 1.6 ms. The explicit stack costs time on trees where recursion fits. On random trees of 10⁵ nodes, in the measurement at the end of this page, it took about three times as long as diameterRecursive.
Interviewer: Can you return the path itself, not only its length?
The Candidate’s answer
Candidate: Each call also returns the deepest leaf below its node. At the best turning node, I keep the two leaves its children returned. Then a walk up from each leaf to the turning node gives the path, if I record each node’s parent. It’s still O(n).
This version isn’t in the lab.
Interviewer: What if a node can have any number of children?
The Candidate’s answer
Candidate: The same pass works with the two largest child heights instead of left and right. Finding the two largest is one loop over the children, so it’s still O(n) in all.
This version isn’t in the lab.
Two mistakes are common here:
- Counting nodes instead of edges. Recording
left + right + 1gives[1, 2]a diameter of2instead of 1. The two heights already count the edges below the turning node. - Checking only the path through the root. Our example returns
3instead of 4, because its longest path turns at node 2. Record a candidate at every node.
Lab folder: module-07/0543-diameter-of-binary-tree/ in the course repository.
102. Binary Tree Level Order Traversal
102. Binary Tree Level Order Traversal is rated Medium. You get the root of a binary tree. Return its values grouped by level: one array per level, from the root’s level down, each read left to right.
0 ≤ n ≤ 2000nodes-1000 ≤ Node.val ≤ 1000
The signature is function levelOrder(root: TreeNode | null): number[][]. Try it on LeetCode first.
Hint
Every node on a level is a child of some node on the level above, in the same left-to-right order.
Interviewer: Return this tree’s values, level by level.
Candidate: Left to right within each level?
Interviewer: Yes.
Candidate: For an empty tree, do I return [] or [[]]?
Interviewer: [].
Candidate: How many nodes?
Interviewer: Up to 2,000.
Candidate: Then even O(n²) is 4 × 10⁶ steps, which fits. I’ll still aim for O(n). Here’s my example and three edge cases.
tree expected
[1, 2, 3, null, 4, 5] [[1], [2, 3], [4, 5]] 4 and 5: different parents
[] []
[-1000, 1000] [[-1000], [1000]] the value limits
a chain of 2,000 2,000 levels of one value each
Candidate: The naive solution finds the height, then collects each level separately. For depth d, it walks down from the root and keeps the nodes exactly d steps down, left before right.
function height(node: TreeNode | null): number {
if (node === null) return 0;
return 1 + Math.max(height(node.left), height(node.right));
}
function collectAtDepth(node: TreeNode | null, depth: number, out: number[]): void {
if (node === null) return;
if (depth === 0) { out.push(node.val); return; }
collectAtDepth(node.left, depth - 1, out);
collectAtDepth(node.right, depth - 1, out);
}
// O(n·h) time, O(n²) on a chain: each level walks down from the root again. O(h) memory besides the output.
export function levelOrderByDepthScan(root: TreeNode | null): number[][] {
const levels: number[][] = [];
const h = height(root);
for (let depth = 0; depth < h; depth++) {
const values: number[] = [];
collectAtDepth(root, depth, values);
levels.push(values);
}
return levels;
}
Candidate: Each level walks again over every level above it. That’s O(n·h) time, O(n²) on a chain: about 2 × 10⁶ steps at 2,000 nodes. It fits. Memory is O(h) besides the output.
In atlimit.ts, levelOrderByDepthScan took 23.9 ms on the chain of 2,000. The recursion is 2,000 calls deep there, which the call stack holds.
Interviewer: What does it repeat?
Candidate: To find level d, it walks levels 0 to d − 1 again. But level d is the children of level d − 1, in order. So I build each level from the one before, the way maxDepth counted levels in 104, and this time I keep the values.
That’s the breadth-first search from 104’s follow-up.
// O(n) time: each node is read once, as part of its level. O(w) memory besides the output (w = widest level).
function levelOrder(root: TreeNode | null): number[][] {
const levels: number[][] = [];
let level: TreeNode[] = root ? [root] : [];
while (level.length > 0) {
const values: number[] = [];
const next: TreeNode[] = [];
for (const node of level) {
values.push(node.val);
if (node.left) next.push(node.left);
if (node.right) next.push(node.right);
}
levels.push(values);
level = next;
}
return levels;
}
export { levelOrder };
Interviewer: Trace your example.
Figure 5 shows each pass of the while loop on [1, 2, 3, null, 4, 5].
level values next
[1] [1] [2, 3]
[2, 3] [2, 3] [4, 5] 2 adds its right child, then 3 its left
[4, 5] [4, 5] []
result [[1], [2, 3], [4, 5]]
Figure 5: the next level is built from the current one, left to right, so no level is ever searched for from the root.
Candidate: For [], level starts empty, the loop doesn’t run, and I return [].
Interviewer: Final cost?
Candidate: O(n) time: each node is read once, on its own level. O(w) memory besides the output, where w is the widest level.
We build one array per level instead of using one array as a queue with shift(). shift() moves every remaining element, so a queue on it can cost O(n) per step. DSA Module 6 measured it on a tree of 100,000 nodes, where the walk took 581 ms with shift() and 8 ms with a real queue.
Interviewer: Now alternate the direction: left to right, then right to left, and so on.
The Candidate’s answer
Candidate: I build the levels the same way and reverse the values of every second level before I store them. It’s still O(n) time.
That’s LeetCode’s 103. Binary Tree Zigzag Level Order Traversal, which this course doesn’t cover. This version isn’t in the lab.
Interviewer: What would someone standing on the right of the tree see?
The Candidate’s answer
Candidate: The last value of each level. Same loop, O(n) time.
That’s LeetCode’s 199. Binary Tree Right Side View, which this course doesn’t cover. This version isn’t in the lab.
Interviewer: Could you do it with depth-first search?
The Candidate’s answer
Candidate: Yes. I pass the depth down and push each value into levels[depth], creating that array the first time. Left before right keeps each level in order. It’s O(n) time, but the recursion is h calls deep, which is fine at 2,000 nodes.
This version isn’t in the lab.
Two mistakes are common here:
- One queue with no level boundary. Reading every node into one list loses where each level ends. Our example returns
[[1,2,3,4,5]]instead of[[1],[2,3],[4,5]]. Handle one level at a time, or record the queue’s length when each level starts. shift()on a large array. The output is right, but eachshift()moves every remaining node, so a wide tree costs O(n²). Build one array per level, or read the queue with a moving index.
Lab folder: module-07/0102-binary-tree-level-order-traversal/ in the course repository.
98. Validate Binary Search Tree
98. Validate Binary Search Tree is rated Medium. You get the root of a binary tree. Decide whether it is a binary search tree: at every node, every value in its left subtree is smaller and every value in its right subtree is larger. No two values may be equal.
1 ≤ n ≤ 10^4nodes-2^31 ≤ Node.val ≤ 2^31 - 1
The signature is function isValidBST(root: TreeNode | null): boolean. Try it on LeetCode first.
Hint
A node deep in the left subtree of 8 must be smaller than 8, whatever its parent is. What range must each node fall in?
Interviewer: Tell me whether this tree is a valid binary search tree.
A binary search tree (BST) is a binary tree where, at every node, the values in the left subtree are smaller and the values in the right subtree are larger. DSA Module 6 builds one.
Candidate: Can two values be equal?
Interviewer: No. An equal value makes the tree invalid.
Candidate: What range do the values cover?
Interviewer: The full 32-bit signed range.
Candidate: Then I can’t use -2³¹ to mean “no bound”, because it’s a real value. I’ll use -Infinity and Infinity. How big, and can it be a chain?
Interviewer: Up to 10⁴ nodes. And yes: insert sorted values into a BST, and each one becomes the right child of the one before.
Candidate: Here’s my example and four edge cases.
tree expected
[8, 4, 12, 2, 6, 10, 14] true
[8, 4, 12, 2, 9] false 9 is right of 4, but inside 8's left
[2, 2] false equal values
[-2^31, null, 2^31 - 1] true the value limits
a right chain 1, 2, ..., 10^4 true sorted values
Pause and predict. Does a check that compares each node only with its two children accept [8, 4, 12, 2, 9]?
Candidate: It would accept it, and that’s wrong. 9 is larger than its parent 4, so that pair looks fine. But 9 is in 8’s left subtree, so it must be smaller than 8.
Candidate: So the naive solution checks the definition at every node. The largest value in the left subtree must be below the node, and the smallest in the right subtree above it.
function subtreeMin(node: TreeNode): number {
let min = node.val;
if (node.left) min = Math.min(min, subtreeMin(node.left));
if (node.right) min = Math.min(min, subtreeMin(node.right));
return min;
}
function subtreeMax(node: TreeNode): number {
let max = node.val;
if (node.left) max = Math.max(max, subtreeMax(node.left));
if (node.right) max = Math.max(max, subtreeMax(node.right));
return max;
}
// O(n·h) time, O(n²) on a chain: every node scans both of its subtrees again. O(h) memory: the call stack.
export function isValidBSTScanSubtrees(root: TreeNode | null): boolean {
if (root === null) return true;
if (root.left && subtreeMax(root.left) >= root.val) return false;
if (root.right && subtreeMin(root.right) <= root.val) return false;
return isValidBSTScanSubtrees(root.left) && isValidBSTScanSubtrees(root.right);
}
Candidate: Every node scans its whole subtree again, so it’s O(n·h) time. On a chain of 10⁴, that’s about 5 × 10⁷ steps, inside the budget. Memory is O(h).
With the larger stack, isValidBSTScanSubtrees took 519.4 ms on the chain of 10⁴ in atlimit.ts. With the default stack, it threw RangeError, like 543’s naive answer.
Interviewer: What does it repeat?
Candidate: Every node’s subtree is scanned once for each node above it. But the rule a node must obey only comes from its ancestors. Going left from a node, its value becomes an upper bound; going right, a lower bound.
Candidate: So I pass the bounds down. Each node is checked once, against the tightest bounds all its ancestors set.
// O(n) time: each node is checked once against the open range its ancestors allow. O(h) memory: the call stack.
export function isValidBSTBounds(root: TreeNode | null): boolean {
function inRange(node: TreeNode | null, low: number, high: number): boolean {
if (node === null) return true;
if (node.val <= low || node.val >= high) return false;
return inRange(node.left, low, node.val) && inRange(node.right, node.val, high);
}
return inRange(root, -Infinity, Infinity);
}
The lab names this function isValidBSTBounds. The version to paste into LeetCode is isValidBST, in the answer to the first follow-up below.
Interviewer: Trace the invalid example.
Figure 6 shows each call of inRange on [8, 4, 12, 2, 9], in the order they run.
node low high check
8 -Infinity Infinity ok
4 -Infinity 8 ok
2 -Infinity 4 ok
9 4 8 9 >= 8: return false
Figure 6: 9 inherits the upper bound 8 from the root, so the check catches a node that its own parent accepts.
Candidate: The && stops there, so 12 is never checked. For [2, 2], the left child must be below 2, and 2 <= low || 2 >= high is true, so it fails. The range is open at both ends, which is what rejects equal values.
Interviewer: Final cost?
Candidate: O(n) time: each node is checked once, and the walk stops at the first failure. O(h) memory for the waiting calls.
Interviewer: The tree can be that chain of 10⁴ sorted values. Does your code handle it?
The Candidate’s answer
Candidate: No. In atlimit.ts, isValidBSTBounds threw RangeError: Maximum call stack size exceeded on the chain. In the run of stack-depth.ts, it handled 7,759 nodes on a first call, and 10⁴ only after the warm-up.
Candidate: With my own stack, the simplest check uses another fact. If I list a BST’s values left subtree first, then the node, then the right subtree, they come out sorted. And if they come out strictly increasing, the tree is a BST. So I walk the tree in that order and compare each value with the one before.
An in-order walk visits a node’s left subtree, then the node, then its right subtree. With an explicit stack, it goes left as far as it can, pushing each node, then pops one, visits it, and continues in its right subtree. DSA Module 6 traces it step by step.
// O(n) time: in-order visits each node once, and a BST's in-order is strictly increasing.
// O(h) memory: the explicit stack holds the left spine of the path; no recursion.
function isValidBST(root: TreeNode | null): boolean {
const stack: TreeNode[] = [];
let node = root;
let previous = -Infinity;
while (node !== null || stack.length > 0) {
while (node !== null) {
stack.push(node);
node = node.left;
}
node = stack.pop()!;
if (node.val <= previous) return false;
previous = node.val;
node = node.right;
}
return true;
}
export { isValidBST };
Figure 7 traces it on [8, 4, 12, 2, 9]. The stack is listed bottom first.
pushed pop previous stack after
8, 4, 2 2 -Infinity [8, 4]
- 4 2 [8]
9 9 4 [8]
- 8 9 [] 8 <= 9: return false
Figure 7: in-order puts 9 before 8, and a value that isn’t larger than the one before it proves the tree is not a BST.
Candidate: It’s O(n) time and O(h) memory, on the heap. In atlimit.ts, isValidBST returned true on the chain of 10⁴ in 0.2 ms.
Interviewer: What if equal values were allowed, but only on the right?
The Candidate’s answer
Candidate: In the bounds version, a right child may equal the lower bound, so that test becomes node.val < low, and the upper bound stays strict. The in-order check can’t make this change alone. [2, 2] and [2, null, 2] both list as 2, 2, but only the second one has the equal value on the right.
This version isn’t in the lab.
Interviewer: Can you check it with O(1) extra memory?
The Candidate’s answer (stretch)
Candidate: There’s an in-order walk that needs no stack, Morris’s traversal. Before it goes left, it links the rightmost node of the left subtree back to the current node, so it can find its way back up. It removes the link on the second visit. It’s O(n) time and O(1) extra memory, but it changes the tree while it runs.
J. M. Morris published it in 1979, in Information Processing Letters. This version isn’t in the lab.
Two mistakes are common here:
- Comparing each node only with its children.
[8, 4, 12, 2, 9]returnstrueinstead offalse. Pass the bounds down from every ancestor, or check the in-order listing. - Using
nullfor “no bound” and testing it as true or false. Withif (low && node.val <= low), a bound of 0 counts as no bound.[0, null, 0]returnstrueinstead offalse. Compare withnullexplicitly, or use-InfinityandInfinity.
Lab folder: module-07/0098-validate-binary-search-tree/ in the course repository.
230. Kth Smallest Element in a BST
230. Kth Smallest Element in a BST is rated Medium. You get the root of a binary search tree and a number k. Return the k-th smallest value in the tree, counting from 1.
1 ≤ k ≤ n ≤ 10^40 ≤ Node.val ≤ 10^4- the page’s follow-up: if the tree changes often and the k-th smallest is asked often, how would you make it faster?
The signature is function kthSmallest(root: TreeNode | null, k: number): number. Try it on LeetCode first.
Hint
Which walk from 98 lists a BST’s values in sorted order?
Interviewer: Return the k-th smallest value in this BST.
Candidate: Counting from 1, so k = 1 is the minimum?
Interviewer: Yes.
Candidate: Is k always between 1 and the number of nodes?
Interviewer: Yes.
Candidate: Can values repeat?
Interviewer: Assume they don’t.
Candidate: How big, and can it be a chain?
Interviewer: Up to 10⁴ nodes, and yes.
Candidate: Here’s my example, the same tree with three values of k, and one more edge case.
tree k expected
[50, 30, 70, 20, 40, 60, 80] 4 50 sorted: 20 30 40 50 60 70 80
[50, 30, 70, 20, 40, 60, 80] 1 20 the minimum
[50, 30, 70, 20, 40, 60, 80] 7 80 k = n, the maximum
[9, 2, 10] 3 10 compare as numbers, not text
Candidate: The naive solution collects every value, sorts them, and takes index k − 1.
// O(n log n) time: collect every value, then sort. O(n) memory. Ignores that the tree is a BST.
export function kthSmallestSort(root: TreeNode | null, k: number): number {
const values: number[] = [];
const stack: TreeNode[] = root ? [root] : [];
while (stack.length > 0) {
const node = stack.pop()!;
values.push(node.val);
if (node.left) stack.push(node.left);
if (node.right) stack.push(node.right);
}
values.sort((a, b) => a - b);
return values[k - 1];
}
Candidate: That’s O(n log n) time for the sort and O(n) memory. At 10⁴ nodes it fits easily. It collects with a stack, so a chain is no problem.
Interviewer: The tree is a BST. Can you use that?
Candidate: The sort puts the values in an order the tree already has. An in-order walk, as in 98, lists a BST’s values sorted, so the sort disappears.
// O(n) time: a full in-order walk, which lists a BST's values already sorted. O(n) memory: the list.
export function kthSmallestFullInOrder(root: TreeNode | null, k: number): number {
const sorted: number[] = [];
function inOrder(node: TreeNode | null): void {
if (node === null) return;
inOrder(node.left);
sorted.push(node.val);
inOrder(node.right);
}
inOrder(root);
return sorted[k - 1];
}
The lab names this function kthSmallestFullInOrder. The version to paste into LeetCode is kthSmallest, in the answer to the first follow-up below.
Interviewer: Trace your example.
Figure 8 shows the tree, the order in which inOrder pushes the values, and the answer for k = 4.
[50]
/ \
[30] [70]
/ \ / \
[20] [40] [60] [80]
pushed in order 20 30 40 50 60 70 80
index 0 1 2 3 4 5 6
k = 4 ^
Figure 8: each node’s value is pushed after its whole left subtree and before its right subtree, so sorted comes out in increasing order.
Candidate: For k = 1, the answer is sorted[0], 20. For k = 7, it’s sorted[6], 80.
Interviewer: Final cost?
Candidate: O(n) time: every node is visited once. O(n) memory for the list, plus O(h) waiting calls.
Interviewer: The tree can be a chain of 10⁴ nodes. And do you need all n values?
The Candidate’s answer
Candidate: On the chain, inOrder is 10⁴ calls deep, which is right at the edge. In atlimit.ts it returned 10000 on a right chain of 10⁴. But in the run of stack-depth.ts it threw RangeError at that size. Over several runs, the longest chain it handled on a first call moved between 10,011 and 10,666. An answer that passes or fails by chance isn’t safe.
Candidate: So I use 98’s in-order walk with an explicit stack. And since I visit the values in order, I count them as I pop them and stop at the k-th, so I never store the list.
// O(h + k) time: walk down the left spine, then stop after the k-th node in order.
// O(h) memory: the explicit stack; no recursion.
function kthSmallest(root: TreeNode | null, k: number): number {
const stack: TreeNode[] = [];
let node = root;
while (node !== null || stack.length > 0) {
while (node !== null) {
stack.push(node);
node = node.left;
}
node = stack.pop()!;
k--;
if (k === 0) return node.val;
node = node.right;
}
throw new Error("k is larger than the number of nodes");
}
export { kthSmallest };
Figure 9 traces it on the same tree with k = 4. The stack is listed bottom first.
pushed pop k after stack after
50, 30, 20 20 3 [50, 30]
- 30 2 [50]
40 40 1 [50]
- 50 0 [] return 50
Figure 9: the walk stops at the fourth pop, so 70, 60 and 80 are never visited.
Candidate: Reaching the smallest value costs h steps down the left side, then each pop is one more value. So it’s O(h + k) time: O(log n + k) on a balanced tree, and O(n) on a chain. Memory is O(h), on the heap.
In atlimit.ts, kthSmallest returned 10000 on the chain with k = 10⁴ in 0.3 ms.
Interviewer: The page’s follow-up: the tree changes often, and the k-th smallest is asked often. How would you make it faster?
The Candidate’s answer (stretch)
Candidate: I’d store in each node the number of nodes in its subtree. To find the k-th smallest, I look at the left subtree’s size t.
Candidate: If t ≥ k, the answer is on the left. If t = k − 1, it’s this node. Otherwise I go right and look for the (k − t − 1)-th smallest there.
Candidate: That’s O(h) per query. Each insert or delete updates the sizes along its path, also O(h). With a tree that keeps itself balanced, h is O(log n), so both are O(log n).
A BST whose nodes store their subtree sizes is an order statistic tree. Sedgewick and Wayne’s Algorithms, section 3.2 writes this select method. This version isn’t in the lab.
Interviewer: What about the k-th largest?
The Candidate’s answer
Candidate: I walk in reverse in-order, right subtree first, then the node, then the left, and stop at the k-th pop. Same costs.
This version isn’t in the lab.
One mistake is common here:
- Sorting numbers with
sort()and no compare function.sort()compares values as text, so 10 comes before 2.[9, 2, 10]with k = 3 returns9instead of 10. Pass(a, b) => a - b, or use the in-order walk and skip the sort.
Lab folder: module-07/0230-kth-smallest-element-in-a-bst/ in the course repository.
105. Construct Binary Tree from Preorder and Inorder Traversal
105. Construct Binary Tree from Preorder and Inorder Traversal is rated Medium. You get two listings of the same binary tree’s values, with no value repeated. One is in preorder and the other in in-order. Rebuild the tree and return its root.
1 ≤ preorder.length ≤ 3000, andinorderhas the same length-3000 ≤ value ≤ 3000- all values are distinct, and the two arrays are always listings of one tree
The signature is function buildTree(preorder: number[], inorder: number[]): TreeNode | null. Try it on LeetCode first.
Hint
The first value in preorder is the root. Where does the root sit in the in-order listing, and what is on each side of it?
Interviewer: Rebuild the tree from these two listings.
A preorder listing gives a node, then its left subtree, then its right subtree. In-order, from 98, gives the left subtree, then the node, then the right subtree.
Candidate: Are the values always distinct?
Interviewer: Yes.
Candidate: Good, because otherwise the tree isn’t unique: [1, 1] and [1, 1] fit both a root with a left child and a root with a right child. Are the two listings always from the same tree?
Interviewer: Yes.
Candidate: How many values?
Interviewer: Up to 3,000.
Candidate: Then O(n²) is about 9 × 10⁶ steps, which fits. I’ll aim for O(n). Here’s my example and two edge cases.
preorder inorder expected
[1, 2, 4, 5, 3, 6] [4, 2, 5, 1, 3, 6] [1, 2, 3, 4, 5, null, 6]
[1, 2, 3] [3, 2, 1] [1, 2, null, 3] a left chain
[1, 2, 3] [1, 2, 3] [1, null, 2, null, 3] a right chain
Candidate: The first preorder value is the root. In the in-order listing, everything before the root is its left subtree and everything after is its right. If the left side has split values, then the next split preorder values are the left subtree’s preorder.
Candidate: The naive solution finds the root with indexOf, cuts both arrays with slice, and builds each side from its pieces.
// O(n²) time on a chain: each call searches inorder with indexOf and copies both arrays with slice.
// O(n²) memory on a chain: every call still waiting holds its own copies.
export function buildTreeSlicing(preorder: number[], inorder: number[]): TreeNode | null {
if (preorder.length === 0) return null;
const rootValue = preorder[0];
const split = inorder.indexOf(rootValue); // values left of it form the left subtree
return new TreeNode(
rootValue,
buildTreeSlicing(preorder.slice(1, split + 1), inorder.slice(0, split)),
buildTreeSlicing(preorder.slice(split + 1), inorder.slice(split + 1)),
);
}
Candidate: Each call searches and copies its whole range, O(n) per node on a chain. That’s O(n²) time, about 9 × 10⁶ steps at 3,000, and O(n²) memory, because every waiting call keeps its own slices. On a balanced tree it’s O(n log n). It fits.
In atlimit.ts, buildTreeSlicing took 19.2 ms on a chain of 3,000.
Interviewer: What does it repeat?
Candidate: Two things. Every call searches the in-order listing again, and every call copies its part of both arrays.
Candidate: A Map from each value to its in-order position replaces the search. A range of in-order positions replaces the copies. And preorder needs no range at all. It lists the whole left subtree before the right, so if I build left before right, the next unused preorder value is the root I need.
// O(n) time: a map gives each root's inorder position in O(1), and ranges replace copies.
// O(n) memory: the map, plus O(h) call frames.
function buildTree(preorder: number[], inorder: number[]): TreeNode | null {
const inorderIndex = new Map<number, number>();
inorder.forEach((value, index) => inorderIndex.set(value, index));
let next = 0; // the next preorder value is always the root of the subtree being built
function build(low: number, high: number): TreeNode | null {
if (low > high) return null;
const rootValue = preorder[next++];
const split = inorderIndex.get(rootValue)!;
const left = build(low, split - 1);
const right = build(split + 1, high);
return new TreeNode(rootValue, left, right);
}
return build(0, inorder.length - 1);
}
export { buildTree };
This one is recursive, and it’s the version to paste. The depth is the tree’s height, at most 3,000 here. In the run of stack-depth.ts, buildTree handled chains of up to 6,170 nodes on a first call, twice the limit. In atlimit.ts it rebuilt the chain of 3,000 in 0.5 ms.
Interviewer: Trace your example.
Figure 10 lists the calls of build that get a non-empty range, in the order they run. The ranges are positions in inorder.
call preorder[next] split left range right range
build(0, 5) 1 3 0..2 4..5
build(0, 2) 2 1 0..0 2..2
build(0, 0) 4 0 empty empty
build(2, 2) 5 2 empty empty
build(4, 5) 3 4 empty 5..5
build(5, 5) 6 5 empty empty
Figure 10: the calls ask for roots in preorder’s own order, because each call builds its left subtree completely before its right.
Candidate: The result is 1 with children 2 and 3; 2 has 4 and 5, and 3 has only a right child, 6. That’s [1, 2, 3, 4, 5, null, 6].
Interviewer: Final cost?
Candidate: O(n) time: each value becomes one node, with an O(1) lookup. O(n) memory for the Map, plus O(h) waiting calls.
Interviewer: Can you do it without recursion?
The Candidate’s answer
Candidate: Yes, with a stack of nodes still waiting for a right child. I walk preorder. While the node on top hasn’t reached its place in the in-order listing, its left side isn’t finished, so the next value is its left child. Once it has, I pop every node whose turn has come in in-order, and the next value is the right child of the last one popped.
// O(n) time: each value is pushed and popped once. O(h) memory: the stack holds nodes still waiting for a
// right child; no recursion.
export function buildTreeStack(preorder: number[], inorder: number[]): TreeNode | null {
if (preorder.length === 0) return null;
const root = new TreeNode(preorder[0]);
const stack: TreeNode[] = [root];
let inIndex = 0;
for (let i = 1; i < preorder.length; i++) {
let parent = stack[stack.length - 1];
if (parent.val !== inorder[inIndex]) {
// the parent's left side is not finished, so the next preorder value is its left child
parent.left = new TreeNode(preorder[i]);
stack.push(parent.left);
} else {
// pop every node whose left side and own value are done in inorder; the last one gets the right child
while (stack.length > 0 && stack[stack.length - 1].val === inorder[inIndex]) {
parent = stack.pop()!;
inIndex++;
}
parent.right = new TreeNode(preorder[i]);
stack.push(parent.right);
}
}
return root;
}
Candidate: It’s O(n) time and O(h) memory, with no Map. But it’s harder to explain at a whiteboard, and at 3,000 nodes the recursion is safe, so I’d offer it only if asked.
In atlimit.ts, it rebuilt the chain of 3,000 in 0.3 ms.
Interviewer: What if you got in-order and postorder instead?
The Candidate’s answer
Candidate: Postorder lists the root last. So I read it from the back, and build the right subtree before the left, since the right subtree comes right before the root. The rest stays the same.
That’s LeetCode’s 106. Construct Binary Tree from Inorder and Postorder Traversal, which this course doesn’t cover. This version isn’t in the lab.
Interviewer: And preorder with postorder?
The Candidate’s answer
Candidate: Then the tree isn’t always unique. A node with one child lists the same in both orders whether the child is on the left or the right. In-order is what tells the two sides apart.
One mistake is common here:
- Building the right subtree first. With the preorder index moving forward, building right before left hands the left subtree’s values to the right side. A split then falls outside its range, and the ranges never shrink. Our example throws
RangeError: Maximum call stack size exceededinstead of returning[1, 2, 3, 4, 5, null, 6]. Build left, then right.
Lab folder: module-07/0105-construct-binary-tree-from-preorder-and-inorder-traversal/ in the course repository.
124. Binary Tree Maximum Path Sum
124. Binary Tree Maximum Path Sum is rated Hard. A path in a binary tree is a sequence of nodes joined by edges, with no node used twice and at least one node. It can start and end anywhere, and it turns at most once. Return the largest sum of node values on any path.
1 ≤ n ≤ 3 × 10^4nodes-1000 ≤ Node.val ≤ 1000
The signature is function maxPathSum(root: TreeNode | null): number. Try it on LeetCode first.
Hint
This is 543 with sums instead of heights. What should a branch with a negative sum add?
Interviewer: Find the largest path sum in this tree.
Candidate: Can a path be a single node?
Interviewer: Yes, but it can’t be empty.
Candidate: So if every value is negative, the answer is the largest single value. Must the path go through the root, or end at a leaf?
Interviewer: Neither.
Candidate: How big are the values and the tree?
Interviewer: -1000 to 1000, and up to 3 × 10⁴ nodes.
Candidate: Then a sum stays within 3 × 10⁷ either way, far inside what a number holds. Here’s my example and three edge cases.
tree expected
[-3, 4, 5, -1, 2, null, -6] 8 2, 4, -3, 5: worth crossing the root
[-7] -7 one negative node
[-2, -1, -3] -1 all negative: the best single node
[1000, -1000, 1000] 2000 leaves out the negative child
Candidate: Like 543, every path has one highest node, where it turns. There its sum is the node’s value, plus the best path going down on each side. If a side’s best is negative, I leave that side out.
Candidate: The naive solution computes those downward bests from scratch for every node.
// Best sum of a path that starts at node and goes down; never below node.val. O(size of the subtree).
function bestDownFrom(node: TreeNode | null): number {
if (node === null) return 0;
return node.val + Math.max(0, bestDownFrom(node.left), bestDownFrom(node.right));
}
// O(n·h) time, O(n²) on a chain: every node recomputes its best downward paths from scratch.
// O(h) memory: the call stack.
export function maxPathSumRecomputing(root: TreeNode | null): number {
if (root === null) return -Infinity;
const throughRoot = root.val + Math.max(0, bestDownFrom(root.left)) + Math.max(0, bestDownFrom(root.right));
return Math.max(throughRoot, maxPathSumRecomputing(root.left), maxPathSumRecomputing(root.right));
}
Candidate: That’s O(n·h) time and O(h) memory. On a chain of 3 × 10⁴, it’s about 4.5 × 10⁸ steps, four and a half times the budget. That’s too slow.
With the larger stack, maxPathSumRecomputing took 5,727.2 ms on the chain of 3 × 10⁴ in atlimit.ts. With the default stack, it threw RangeError. LeetCode doesn’t publish its time limits, but this is far from the milliseconds the other answers take.
Interviewer: What does it repeat?
Candidate: The same as in 543: every node’s best downward sum is recomputed by every node above it. So each call returns its best downward sum to its parent, and on the way it scores the path that turns at its node.
Candidate: The returned value can use only one child, because a path that goes up can’t fork. The score at the node can use both.
// O(n) time: one post-order pass returns each node's best downward gain once. O(h) memory: the call stack.
export function maxPathSumRecursive(root: TreeNode | null): number {
let best = -Infinity;
function gain(node: TreeNode | null): number {
if (node === null) return 0;
const left = Math.max(0, gain(node.left)); // a negative branch is better left out
const right = Math.max(0, gain(node.right));
best = Math.max(best, node.val + left + right); // the path that turns at this node
return node.val + Math.max(left, right); // a path going up can use only one branch
}
gain(root);
return best;
}
The lab names this function maxPathSumRecursive. The version to paste into LeetCode is maxPathSum, in the answer to the first follow-up below.
Interviewer: Trace your example.
Figure 11 lists the calls of gain in the order they finish. left and right are the children’s gains after the clamp at 0.
[-3]
/ \
[4] [5]
/ \ \
[-1] [2] [-6]
node left right turn here best returns
-1 0 0 -1 -1 -1
2 0 0 2 2 2
4 0 2 4 + 0 + 2 = 6 6 6
-6 0 0 -6 6 -6
5 0 0 5 6 5
-3 6 5 -3 + 6 + 5 = 8 8 3
Figure 11: node 4 drops its -1 branch, node 5 drops its -6 branch, and the root scores both of its gains even though it returns only one.
Candidate: For [-7], best starts at -Infinity, so it becomes -7. For [-2, -1, -3], both children clamp to 0 at the root, and the best of -1, -3 and -2 is -1.
Interviewer: Final cost?
Candidate: O(n) time: one call per node. O(h) memory for the waiting calls.
Interviewer: And on a chain of 3 × 10⁴ nodes?
The Candidate’s answer
Candidate: That’s three times the depth that broke 543. In atlimit.ts, maxPathSumRecursive threw RangeError: Maximum call stack size exceeded. In the run of stack-depth.ts, it handled 6,897 nodes on a first call and failed at 3 × 10⁴ even after the warm-up.
Candidate: So I use 543’s explicit stack, with a Map of gains instead of heights.
// O(n) time: each node is pushed and popped once, children before parents. O(n) memory: the gains map;
// no recursion, so a 3 × 10^4-node chain is safe.
function maxPathSum(root: TreeNode | null): number {
let best = -Infinity;
const gains = new Map<TreeNode | null, number>([[null, 0]]);
const stack: TreeNode[] = root ? [root] : [];
while (stack.length > 0) {
const node = stack[stack.length - 1];
if (node.left && !gains.has(node.left)) { stack.push(node.left); continue; }
if (node.right && !gains.has(node.right)) { stack.push(node.right); continue; }
stack.pop();
const left = Math.max(0, gains.get(node.left)!);
const right = Math.max(0, gains.get(node.right)!);
best = Math.max(best, node.val + left + right);
gains.set(node, node.val + Math.max(left, right));
}
return best;
}
export { maxPathSum };
Candidate: O(n) time and O(n) memory for the Map, all on the heap.
In atlimit.ts, maxPathSum returned 450015000 on a chain with values 1 to 3 × 10⁴ in 2.8 ms. That’s the sum of every value, because the whole chain is the best path.
Interviewer: Can you return the path, not only the sum?
The Candidate’s answer
Candidate: For each node, I also store which child its gain came from, or none. At the best turning node, I follow those choices down each side that I kept. It’s still O(n).
This version isn’t in the lab.
Interviewer: What if a path had to start at the root and end at a leaf?
The Candidate’s answer
Candidate: Then there’s no turning point to score. Each node’s best is its value plus the better of its children’s bests, and the answer is the root’s. A leaf must end the path, so a missing child doesn’t count as 0. It’s one pass, O(n).
This version isn’t in the lab.
Three mistakes are common here:
- Not leaving out negative branches. Without the clamp at 0,
[-1, -2, -3]returns-2instead of -1, because the root adds a negative child. TakeMath.max(0, gain)for each child. - Returning both branches to the parent. A parent that adds both of a child’s branches builds a fork, not a path.
[1, 2, null, 3, 4]returns10instead of 9. Return the value plus one branch; score both only at the turn. - Starting
bestat 0. A tree of negative values never beats 0, so[-7]returns0instead of -7. Start at-Infinity.
Lab folder: module-07/0124-binary-tree-maximum-path-sum/ in the course repository.
Measured: Diameter of Binary Tree, recomputed heights against one pass
Diameter of Binary Tree, the problem at the top of this page, is the one this module measures, with bench.ts from DSA Module 1. It runs two shapes. A chain is the worst case for recomputing heights; the chains for the recursive versions stay at 4,000 nodes or fewer, below where they overflow the call stack. Random trees are short and wide, so recursion is safe there.
// Module 7 measurement: Diameter of Binary Tree that recomputes heights at every node, against one pass.
// Run from the repository root: node module-07/measure.ts
import { bench } from "../shared/bench.ts";
import { leftChain, randomTree } from "./trees.ts";
import { diameterRecomputingHeights, diameterRecursive, diameterOfBinaryTree } from "./0543-diameter-of-binary-tree/solution.ts";
let sink = 0; // the timed functions add to it, so their work cannot be skipped
// The chain is the worst case for recomputing: the subtree sizes add up to n²/2.
// Chains stay at 4,000 or less, below where the recursive versions overflow the stack.
bench("diameterRecomputingHeights, left chain", [1_000, 2_000, 4_000], leftChain, (root) => {
sink += diameterRecomputingHeights(root);
});
bench("diameterOfBinaryTree (one pass, explicit stack), left chain", [1_000, 2_000, 4_000], leftChain, (root) => {
sink += diameterOfBinaryTree(root);
});
bench("diameterOfBinaryTree (one pass, explicit stack), left chain past the limit", [10_000, 20_000, 40_000], leftChain, (root) => {
sink += diameterOfBinaryTree(root);
});
// Random shapes (values -100..100): short and bushy, so recursion is safe.
const randomShape = (n: number) => randomTree(n);
bench("diameterRecomputingHeights, random tree", [25_000, 50_000, 100_000], randomShape, (root) => {
sink += diameterRecomputingHeights(root);
});
bench("diameterRecursive (one pass, recursion), random tree", [25_000, 50_000, 100_000], randomShape, (root) => {
sink += diameterRecursive(root);
});
bench("diameterOfBinaryTree (one pass, explicit stack), random tree", [25_000, 50_000, 100_000], randomShape, (root) => {
sink += diameterOfBinaryTree(root);
});
console.log(`\nsink ${sink}`);
bench runs each size once to warm up, then five times on fresh trees, and prints the median and how many times slower each size is than the one before. Building the tree isn’t timed. randomTree in trees.ts adds each node by walking down from the root and turning left or right at random, so the trees of 10⁵ nodes were about 20 levels tall.
Pause and predict. On the chain, by how much should the recomputing version’s time grow each time n doubles? And on the random trees?
Here is what node module-07/measure.ts printed:
diameterRecomputingHeights, left chain
n median ms x prev
1,000 5.53
2,000 22.52 4.1
4,000 94.12 4.2
diameterOfBinaryTree (one pass, explicit stack), left chain
n median ms x prev
1,000 0.07
2,000 0.14 2.0
4,000 0.29 2.1
diameterOfBinaryTree (one pass, explicit stack), left chain past the limit
n median ms x prev
10,000 0.54
20,000 1.28 2.4
40,000 2.18 1.7
diameterRecomputingHeights, random tree
n median ms x prev
25,000 3.81
50,000 8.86 2.3
100,000 19.87 2.2
diameterRecursive (one pass, recursion), random tree
n median ms x prev
25,000 0.53
50,000 1.58 3.0
100,000 3.56 2.3
diameterOfBinaryTree (one pass, explicit stack), random tree
n median ms x prev
25,000 2.14
50,000 4.98 2.3
100,000 11.32 2.3
sink 505954
These numbers come from one run on an Apple M2 laptop with macOS and Node.js 24.22.1. Your numbers will differ, but the ratios should look alike.
On the chain, recomputing grew 4.1 and 4.2 times per doubling, the O(n²) of n²/2 height steps. At 4,000 nodes it was more than 300 times slower than one pass. From 4,000 to 10⁴ nodes is 2.5 times the size, so O(n²) predicts 6.25 times the time, about 590 ms, and atlimit.ts measured 607.0 ms with the larger stack. So at LeetCode’s limit, the naive answer is slow but inside the budget, and the call stack is what stops it.
On the random trees, recomputing grew only 2.2 and 2.3 times per doubling. Each node there recomputes the heights of a short subtree, so the cost is O(n·h) with h about 20, close to O(n log n). It was still 5.6 to 7.2 times slower than the recursive one pass.
The one pass with an explicit stack grew about 2 times per doubling, O(n), and handled a chain of 40,000 nodes in 2.18 ms. The steps of 2.4 and 1.7 start from half a millisecond, a time small enough to move between runs. On random trees of 10⁵ nodes, the recursive one pass took 3.56 ms and the explicit stack 11.32 ms. That’s about three times slower, because the Map and the stack cost time on every node. sink adds up the results, so V8 can’t skip the calls.
Underneath: how deep a tree walk can go in Node.js
JavaScript has no built-in tree. TreeNode is a plain class, each node is an ordinary object with a number and two references, and nothing in the language keeps a tree balanced. So every walk is either a recursion or a loop over those references.
A recursion keeps the current path in V8’s call stack, which is capped in bytes, not in calls. On this arm64 build of Node.js 24.22.1, node --v8-options lists --stack-size with a default of 984 KB. How many calls fit depends on the size of each frame, and on how far the JIT compiler has optimized the function.
In one run of stack-depth.ts, the longest chain each recursive solution in this module handled on a first call ranged from 5,610 nodes (buildTreeSlicing) to 10,666 (kthSmallestFullInOrder). Some handled 10⁴ after a warm-up and others didn’t.
Raising --stack-size only tells V8 how much stack to assume. The operating system’s stack for the main thread is 8 MB on this Mac, and a value above it crashes the process with no error message. atlimit.ts uses 7,500 KB for that reason.
V8 doesn’t run tail calls in constant stack space either, so rewriting a walk as a tail call doesn’t help. DSA Module 6 measures all three effects.
An explicit stack or an array per level lives on the heap, which has no such limit. But it costs time. The measurement above found the Map-based one pass about three times slower than recursion on random trees of 10⁵ nodes. That’s why the recursive answer is still the one to write first, and the explicit stack the one to offer when the limits allow a deep chain.
A BST’s speed depends on its height. With values inserted in random order, a search takes about 1.39 log₂ n comparisons on average (Sedgewick and Wayne, section 3.2). With values inserted in sorted order, the BST is a chain, as in 98’s and 230’s edge cases, and every operation is O(n). DSA Module 6 measures both.
Cheat sheet
Figure 12 maps each problem in this module to the sign that pointed to its solution.
sign in the problem problem the walk cost
mirror every node 226 recursion, swap children O(n)
height of the tree 104 levels (BFS) O(n)
longest path, may skip the root 543 post-order, height up O(n)
values level by level 102 one array per level O(n)
is it a BST 98 in-order, rising values O(n)
k-th smallest in a BST 230 in-order, stop at k O(h+k)
rebuild from preorder and in-order 105 Map of positions, ranges O(n)
largest path sum, may turn 124 post-order, clamp at 0 O(n)
Figure 12: on a tree, each node’s answer comes from its children’s, so one walk visits each node once; only the order of the walk changes.
- Pattern: compute a node’s answer from its children’s; return one value up, and keep a turning answer (diameter, path sum) in a variable outside.
- Chains: when the limits allow a chain deeper than a few thousand nodes, move the recursion to an explicit stack or to levels; 104, 543, 98, 230 and 124 paste their iterative version.
- Signs: a
TreeNodeinput; a question about every subtree; “level by level”; a BST, whose in-order walk is sorted; two listings of one tree. - Final costs: 226, 104, 543, 102, 98, 105 and 124 in O(n) time; 230 in O(h + k). Memory: O(h) for 226, 98 and 230; O(w) for 104 and 102; O(n) for 543, 105 and 124.
- Next: Module 8 works heaps and intervals, starting from a median that’s sorted again on every query.
Sources
- LeetCode problem pages, checked on 2026-11-20: 226, 104, 543, 102, 98, 230, 105, 124, and 101, 103, 106, 110, 111 and 199 for follow-ups.
- Dictionary of Algorithms and Data Structures, NIST: “binary tree”, “height”, “diameter”, “breadth-first search”, “binary search tree”, “preorder traversal”, “inorder traversal” and “postorder traversal”.
- Robert Sedgewick and Kevin Wayne, Algorithms, 4th edition: 3.2 Binary Search Trees (in-order order,
selectby subtree size, the average cost for random keys). - J. M. Morris, “Traversing binary trees simply and cheaply”, Information Processing Letters 9(5), 197–200, 1979, doi:10.1016/0020-0190(79)90068-1.
- Node.js documentation: assert, TypeScript, test runner. V8’s
--stack-sizeand the 8 MB thread stack: nodejs/node#16870.