Courses / DSA Patterns for Working Engineers / Chapter 22
Module 7 · Trees and tries · Chapter 22 of 39
Tree Breadth-First Search: Level by Level
Builds on Graphs: Modelling, Breadth-First and Depth-First Search and Tree Depth-First Search: Recursion That Returns Answers Upward. Next up: Tries: Prefix Trees for Search and Autocomplete.
Part 1 · Introduction to tree breadth-first search
Visiting a tree one level at a time
A building directory lists the ground floor, then the first floor, then the second. That is breadth-first search on a tree: finish every node at one depth before any node at the next.
Depth-first search follows a branch to its end. Breadth-first search (BFS) instead keeps a queue, first in first out, of nodes waiting to be visited. Start with the root in it. Repeatedly take the node at the front, record it, and add its children at the back. Because children join behind everything already waiting, nodes come out in order of depth, and within a depth from left to right. A level is all the nodes at one depth.
The queue is an array with a head index that moves forward, never shift(), exactly as in the graphs chapter. Code blocks follow the convention set out in the first chapter. The tree type, fromLevels and randomTree come from tree.ts in the tree DFS chapter.
Many problems want the nodes grouped by level, not in one flat list. The trick is to take a snapshot of the queue size at the start of each level. Everything in the queue at that moment belongs to the current level, and anything pushed while you work on it belongs to the next. So you process exactly that many nodes and then start again.
// Values level by level, top to bottom, left to right. export function levelOrder(root: TreeNode | null): number[][] { const out: number[][] = [] if (root === null) return out const queue: TreeNode[] = [root] let head = 0 while (head < queue.length) { const size = queue.length - head // nodes on this level, fixed now const level: number[] = [] for (let i = 0; i < size; i++) { const n = queue[head++] level.push(n.val) if (n.left !== null) queue.push(n.left) if (n.right !== null) queue.push(n.right) } out.push(level) } return out }
level.ts: values grouped by level
Watching the queue
const root = fromLevels([1, 2, 3, 4, 5, null, 6, 7]) console.log(levelOrder(root)) console.log(levelOrder(null)) console.log(queueProfile(root))
A seven-node tree, an empty tree, and the queue sizes
[ [ 1 ], [ 2, 3 ], [ 4, 5, 6 ], [ 7 ] ] [] { atStart: [ 1, 2, 3, 1 ], peak: 3 }
Output of one run
Watch for the queue holding exactly one level each time the loop starts
Read it as steps
each pass takes one level off the queue
The third line of output lists how many nodes were waiting when each level started: 1, 2, 3 and 1. The last level has one node, 7, which hangs below 4. The most that ever waited at once was 3. The scene uses a full tree of seven nodes, so its levels hold 1, 2 and 4.
The number size is fixed before the inner loop runs, because queue.length - head is read once. Reading queue.length inside the loop condition instead would keep growing as children are added, and the levels would run together.
How much memory the queue needs
How many nodes wait in the queue at once depends on the shape of the tree. At any moment the queue holds the unprocessed rest of one level plus the children already added for the next. It therefore never holds more than two neighbouring levels together, and it holds a whole level when that level starts. The peak lies between the widest level and the largest sum of two neighbouring levels, so the widest level of the tree sets the scale.
// How many nodes wait in the queue when each level starts, and the most // that ever wait at once. export function queueProfile(root: TreeNode | null) { const atStart: number[] = [] let peak = 0 if (root === null) return { atStart, peak } const queue: TreeNode[] = [root] let head = 0 while (head < queue.length) { const size = queue.length - head atStart.push(size) peak = Math.max(peak, size) for (let i = 0; i < size; i++) { const n = queue[head++] if (n.left !== null) queue.push(n.left) if (n.right !== null) queue.push(n.right) peak = Math.max(peak, queue.length - head) } } return { atStart, peak } }
level.ts: queue sizes at the start of each level, and the peak
// A complete tree of 1,023 nodes, and a chain of 1,000. function complete(depth: number, next = { v: 1 }): TreeNode | null { if (depth === 0) return null const n = new TreeNode(next.v++) n.left = complete(depth - 1, next) n.right = complete(depth - 1, next) return n } let chain = new TreeNode(0) for (let i = 1; i < 1000; i++) chain = new TreeNode(i, chain) const wide = queueProfile(complete(10)) const tall = queueProfile(chain) console.log('complete tree: widest level', Math.max(...wide.atStart), 'peak waiting', wide.peak) console.log('chain: levels', tall.atStart.length) console.log('chain: peak waiting', tall.peak)
A complete tree of 1,023 nodes and a chain of 1,000
complete tree: widest level 512 peak waiting 512 chain: levels 1000 chain: peak waiting 1
Output of one run
The complete tree has about half of its nodes on its last level, 512 of 1,023, and the queue peaks at that figure. The chain has 1,000 levels of one node each, and never holds more than one. A depth-first search has the opposite profile: its stack is as deep as the tree is tall, which is small for the complete tree and 1,000 for the chain. Pick the search whose worst case your input is unlikely to hit.
One detail: the head-index queue never shrinks, because consumed nodes stay in the array. For a tree that fits in memory this is harmless, but the array ends up holding every node. If that matters, keep two arrays instead, the current level and the next, and drop the old one at the end of each pass.
Part 2 · Rooms floor by floor
Listing a building by floor
A building is drawn as a tree: the lobby at the top, the rooms it leads to below, and so on. A facilities team wants a list of the rooms on each floor, and a second list that walks the floors in a snake, left to right on one floor and right to left on the next, as a guard might on a patrol.
The first list is levelOrder from the previous lesson, so nothing new is needed. The zigzag is the same list with every second level reversed. The simplest correct way to get it is to build each level normally, left to right, and reverse the odd-numbered ones when they are done.
// Level order, but every second level is read right to left. export function zigzag(root: TreeNode | null): number[][] { return levelOrder(root).map((level, i) => { return i % 2 === 1 ? level.reverse() : level }) }
level.ts: reverse every second level
Why not add to the front of each odd level as you go? unshift inserts at the front, and every element already in the array has to move along, so building a level of w nodes this way can cost about w squared steps. A single reverse at the end costs w. The saving is small for small levels and large for wide ones.
Reversing a level never changes which nodes belong to it, only the order in which they are listed, so the queue itself is untouched and still processes nodes left to right.
Running it
// A building: floors listed left to right, then in zigzag order. const building = fromLevels([10, 20, 30, 40, 50, 60, 70]) console.log(zigzag(building)) const stairs = fromLevels([1, 2, null, 3, null, 4]) console.log(zigzag(stairs), zigzag(null))
A seven-room building, and a staircase of four
[ [ 10 ], [ 30, 20 ], [ 40, 50, 60, 70 ] ] [ [ 1 ], [ 2 ], [ 3 ], [ 4 ] ] []
Output of one run
The full building has three floors. The second is reversed to 30, 20, and the third stays left to right. The staircase, a chain where each room has one child, has four floors of one room each. Reversing a list of one changes nothing, so its zigzag matches its level order, and an empty tree gives an empty list.
Levels can also be found without a queue. A depth-first walk passes the depth of the current node along, and appends the node's value to the list for that depth, adding a new list when it reaches a depth it has not seen. The lists come out in the same left-to-right order because the walk always goes left before right.
// Levels again, depth first: a node's depth says which list gets it. export function levelOrderDfs(root: TreeNode | null): number[][] { const out: number[][] = [] const walk = (n: TreeNode | null, depth: number): void => { if (n === null) return if (depth === out.length) out.push([]) out[depth].push(n.val) walk(n.left, depth + 1) walk(n.right, depth + 1) } walk(root, 0) return out }
level.ts: levels by a depth-first walk
Both give the same answer, and the test checks it. Which to choose depends on what comes next. If the next step is level by level, such as zigzag or averages, the queue reads more naturally. If the problem is already recursive, carrying the depth is just as easy.
The nearest leaf, and bottom-up order
Two more questions use the same loop. The first lists the levels from the bottom of the tree up: take the normal list and reverse the order of the levels, keeping each level left to right. The second asks for the nearest leaf, the fewest nodes on a path from the root down to any leaf. A breadth-first search suits it, because nodes come out in order of depth: the first leaf taken from the queue is the nearest, and the search can stop there. A depth-first search cannot stop early, because it has to look at every branch before it knows which is shortest.
A leaf has no children, so a root with one child is not a leaf, and a tree of just that root and its child has nearest-leaf depth 2, not 1. The count is in nodes, as in the maximum depth lesson of the previous chapter.
// The fewest nodes on a path from the root down to a leaf. A leaf has // no children, so a root with one child is not a leaf. `stats` counts // the nodes taken from the queue. export function minDepth( root: TreeNode | null, stats = { taken: 0 }, ): number { if (root === null) return 0 const queue: TreeNode[] = [root] let head = 0 for (let depth = 1; head < queue.length; depth++) { const size = queue.length - head for (let i = 0; i < size; i++) { const n = queue[head++] stats.taken++ if (n.left === null && n.right === null) return depth if (n.left !== null) queue.push(n.left) if (n.right !== null) queue.push(n.right) } } return 0 // not reached: every tree has a leaf }
near.ts: stop at the first leaf taken from the queue
// Levels from the bottom of the tree up, each still left to right. export function levelsFromBottom(root: TreeNode | null): number[][] { return levelOrder(root).reverse() }
near.ts: levels from the bottom up
// A chain of 1,000 nodes hangs on the right; the left child is a leaf. let chain = new TreeNode(0) for (let i = 1; i < 1000; i++) chain = new TreeNode(i, chain) const root = new TreeNode(-1, new TreeNode(-2), chain) const stats = { taken: 0 } console.log('nearest leaf at depth', minDepth(root, stats)) console.log('nodes taken from the queue:', stats.taken, 'of 1002') console.log(levelsFromBottom(fromLevels([1, 2, 3, 4, null, null, 5])))
A shallow leaf beside a chain of 1,000 nodes
nearest leaf at depth 2 nodes taken from the queue: 2 of 1002 [ [ 4, 5 ], [ 2, 3 ], [ 1 ] ]
Output of one run
The right child starts a chain of 1,000 nodes, but the left child is a leaf, so the search stops after taking 2 of the 1,002 nodes. A tree with no leaf near the top gives no such saving, and then the search takes every node, which costs what a full level-order pass costs. The recursive check in the test visits every branch and takes the smaller answer, with infinity standing in for a missing child so that a root with one child is not counted as a leaf.
Checking the three versions
The tests compare the queue version with the two-array version and the depth-keyed version on 1,500 random trees, and check that every node appears exactly once. The zigzag is compared with the plain level order, level by level: odd levels must be reversed copies and even levels equal.
test('edge cases', () => { assert.deepEqual(levelOrder(null), []) assert.deepEqual(levelOrder(new TreeNode(9)), [[9]]) assert.deepEqual(zigzag(null), []) const full = fromLevels([1, 2, 3, 4, 5, 6, 7]) assert.deepEqual(zigzag(full), [[1], [3, 2], [4, 5, 6, 7]]) })
level.test.ts: edge cases
test('the two-array version and the queue agree', () => { const rand = mulberry32(81) for (let t = 0; t < 1500; t++) { const n = Math.floor(rand() * 20) const root = randomTree(rand, n) const levels = levelOrder(root) assert.deepEqual(levelOrderSwap(root), levels) assert.deepEqual(levelOrderDfs(root), levels) // Values are 1..n, so each node must appear exactly once. const sorted = levels.flat().sort((a, b) => a - b) assert.deepEqual(sorted, Array.from({ length: n }, (_, i) => i + 1)) } }) test('zigzag reverses exactly the odd levels', () => { const rand = mulberry32(82) for (let t = 0; t < 1000; t++) { const root = randomTree(rand, 1 + Math.floor(rand() * 20)) const plain = levelOrder(root) const zz = zigzag(root) plain.forEach((level, i) => { const want = i % 2 === 1 ? [...level].reverse() : level assert.deepEqual(zz[i], want) }) } })
level.test.ts, continued: queue, swap, depth-keyed, zigzag
✔ edge cases (1.1995ms) ✔ the two-array version and the queue agree (16.651ms) ✔ zigzag reverses exactly the odd levels (5.8646ms) ℹ tests 3 ℹ pass 3 ℹ fail 0
Output of one run; the millisecond figures vary
The edge cases are the empty tree and a one-node tree. A tree with 20 nodes of random shape may be tall and thin or short and bushy, and the checks hold for both. Related on LeetCode: Binary Tree Level Order Traversal, Binary Tree Zigzag Level Order Traversal.
Why reverse each odd level at the end and not insert at the front?
- Inserting at the front can move every element already in the list each time, so a level of w nodes can cost about w squared. One reverse costs about w.
Part 3 · What a relay inspector sees from the right
The problem
Relay stations form a tree, with the control room at the top. An inspector stands to the right of the whole structure and looks across. At each level the inspector sees the rightmost station and nothing else, because the stations to its left are hidden behind it. List what is seen from the top level down.
The answer is the last node of every level. A level-order pass already knows where each level ends: it is the node whose index within the level is size - 1. Record that node's value when the loop reaches it, and carry on as before.
// The last node of every level: what you see standing on the right. export function rightView(root: TreeNode | null): number[] { const out: number[] = [] if (root === null) return out const queue: TreeNode[] = [root] let head = 0 while (head < queue.length) { const size = queue.length - head for (let i = 0; i < size; i++) { const n = queue[head++] if (i === size - 1) out.push(n.val) if (n.left !== null) queue.push(n.left) if (n.right !== null) queue.push(n.right) } } return out }
view.ts: the last node of each level
Note that the visible station is not always on the right edge of the tree. A node that is the left child of its parent can be the one seen, if no node lies to its right at the same depth.
Each node is visited once, so the time is proportional to the number of nodes, and the queue needs room for about the widest level. The view from the left is the same loop with the test i === 0 in place of i === size - 1. Views from above or below need each node's horizontal position as well, which is a different problem.
| Term | Meaning |
|---|---|
| level | all nodes at the same depth |
| snapshot | the queue size read once at the start of a level |
| view |
Seeing it in the scene
Watch for only the last node of each level reaching the output
Read it as steps
the last node of a level goes to the output strip
In the scene, the fourth level has a single station, 6, which is the left child of 4. Nothing sits to its right on that level, so it is the one the inspector sees. A solution that simply followed right children from the top would miss it.
// A relay tree. Station 6 hangs on the left of 4, yet it is the only // node on its level, so it is visible from the right. // 1 // / \ // 2 3 // \ / // 4 5 // / // 6 const relay = fromLevels([1, 2, 3, null, 4, 5, null, 6]) console.log('queue:', rightView(relay)) console.log('walk: ', rightViewDfs(relay))
A relay tree where a left child is visible
queue: [ 1, 3, 5, 6 ] walk: [ 1, 3, 5, 6 ]
Output of one run
The first line is the queue version. The second is a depth-first version, described next, and they agree.
A depth-first version, and a check
The same list falls out of a depth-first walk that visits the right child before the left. The first node reached at each new depth is then the rightmost one on that level, because any node further right at the same depth sits in a subtree that was visited earlier. The walk needs only the depth and the number of levels seen so far.
// Depth first, right child first: the first node reached on each new // depth is the one the right side sees. export function rightViewDfs(root: TreeNode | null): number[] { const out: number[] = [] const walk = (n: TreeNode | null, depth: number): void => { if (n === null) return if (depth === out.length) out.push(n.val) walk(n.right, depth + 1) walk(n.left, depth + 1) } walk(root, 0) return out }
view.ts: right child first, first node per depth
The two versions use different structures, a queue and recursion, and different ideas, last on the level and first from the right. That makes them a good pair for checking each other. The test runs both on 2,000 random trees and requires equal results. It also checks a tree whose nodes all hang to the left.
test('edge cases', () => { assert.deepEqual(rightView(null), []) assert.deepEqual(rightViewDfs(null), []) assert.deepEqual(rightView(fromLevels([5])), [5]) // A left-only chain: every node is visible. const left = fromLevels([1, 2, null, 3, null, 4]) assert.deepEqual(rightView(left), [1, 2, 3, 4]) assert.deepEqual(rightViewDfs(left), [1, 2, 3, 4]) }) test('the queue and the right-first walk agree', () => { const rand = mulberry32(83) for (let t = 0; t < 2000; t++) { const root = randomTree(rand, Math.floor(rand() * 25)) assert.deepEqual(rightView(root), rightViewDfs(root)) } })
view.test.ts
✔ edge cases (1.7717ms) ✔ the queue and the right-first walk agree (11.6962ms) ℹ tests 2 ℹ pass 2 ℹ fail 0
Output of one run; the millisecond figures vary
For the left-only chain 1, 2, 3, 4 every node is the only one on its level, so all four are seen. The empty tree has an empty view. Related on LeetCode: Binary Tree Right Side View.
Which node of each level does the right-side view report?
- The last one in left-to-right order, the node at index
size - 1of the level.
Part 4 · Average pay per band
The problem
A company's reporting tree has one person at the top, their reports below, and so on. Each level is a pay band, and HR wants the average monthly pay of each band, from the top level down. Pay is a whole number of rupees.
Level order gives the groups. For each level add the values and divide by the size, which is already known from the snapshot. The sum is a running total while the level is processed, so the lists of values are not needed.
// The average value on every level. Values are whole numbers (rupees). // Throws if a level's total stops being an exact integer. export function levelAverages(root: TreeNode | null): number[] { const out: number[] = [] if (root === null) return out const queue: TreeNode[] = [root] let head = 0 while (head < queue.length) { const size = queue.length - head let sum = 0 for (let i = 0; i < size; i++) { const n = queue[head++] if (!Number.isSafeInteger(n.val)) { throw new RangeError('not a safe integer') } sum += n.val if (!Number.isSafeInteger(sum)) { throw new RangeError('level total is too large') } if (n.left !== null) queue.push(n.left) if (n.right !== null) queue.push(n.right) } out.push(sum / size) } return out }
band.ts: the average of every level
The averages can be fractions, such as 14.5, and a fraction is fine as a floating-point result. The sums are the part that needs care.
Each node is visited once and added once, so the time is proportional to the number of nodes. The queue needs room for about the widest level, as before. Nothing is stored per level except the single running total, which is why the list of values is never built.
| Term | Meaning |
|---|---|
| band | one level of the pay tree |
| safe integer | a whole number JavaScript can represent exactly and tell apart from its neighbours |
When a sum stops being exact
JavaScript numbers are 64-bit floating-point values. They hold every whole number exactly up to 2^53 - 1, which is Number.MAX_SAFE_INTEGER, and beyond that some whole numbers have no representation, so arithmetic silently rounds. A total that crosses the limit is wrong without any warning.
Real pay figures never reach that size. But the principle matters when summing many large values, such as paise or counters, so the function checks. If a value is not a safe integer, or a running total stops being one, it throws a RangeError. An error is better than a quietly wrong number.
const big = Number.MAX_SAFE_INTEGER // 2^53 - 1 console.log('2^53 - 1 is', big) console.log('plain sum :', big + 1 + 1) console.log('exact sum :', BigInt(big) + 1n + 1n) console.log(Number.isSafeInteger(big + 1), Number.isSafeInteger(big)) try { levelAverages(fromLevels([0, big, 1, 1])) } catch (e) { console.log((e as Error).name + ':', (e as Error).message) }
Adding past 2^53 - 1, and the guard
2^53 - 1 is 9007199254740991 plain sum : 9007199254740992 exact sum : 9007199254740993n false true RangeError: level total is too large
Output of one run
The plain sum of the limit plus 1 plus 1 prints 9007199254740992, but the true total is 9007199254740993, which the BigInt sum shows. Number.isSafeInteger is true for the limit and false for the limit plus 1, so the guard fires before the total can be wrong.
If you need such totals exactly, sum with BigInt and convert at the end, or use a different representation. That choice belongs to the data, not to the traversal.
Running and checking
// Monthly pay in rupees for each band of a reporting tree. const pay = fromLevels([ 90000, 40000, 50000, 28000, 32000, 35000, 31000, ]) console.log(levelAverages(pay))
Pay in rupees for a seven-person tree
[ 90000, 45000, 31500 ]
Output of one run
The top band has one person on 90,000. The second has two, 40,000 and 50,000, and averages 45,000. The third has four, averaging 31,500.
The check does not use a queue at all. It walks the tree depth first and keeps a total and a count for each depth, then divides. That is a different method with different arithmetic order, and it must match on 2,000 random trees with positive and negative values.
// Totals and counts per depth, by a depth-first walk. function brute(root: TreeNode | null): number[] { const sums: number[] = [] const counts: number[] = [] const walk = (n: TreeNode | null, d: number): void => { if (n === null) return sums[d] = (sums[d] ?? 0) + n.val counts[d] = (counts[d] ?? 0) + 1 walk(n.left, d + 1) walk(n.right, d + 1) } walk(root, 0) return sums.map((s, d) => s / counts[d]) }
Totals and counts per depth
test('edge cases', () => { assert.deepEqual(levelAverages(null), []) assert.deepEqual(levelAverages(new TreeNode(-7)), [-7]) assert.deepEqual(levelAverages(fromLevels([5, 12, 30])), [5, 21]) assert.throws(() => levelAverages(new TreeNode(1.5)), RangeError) const big = Number.MAX_SAFE_INTEGER const tooBig = fromLevels([0, big, 1]) assert.throws(() => levelAverages(tooBig), RangeError) }) test('matches the depth-keyed totals on random trees', () => { const rand = mulberry32(84) for (let t = 0; t < 2000; t++) { const root = randomTree(rand, Math.floor(rand() * 20), 1000) assert.deepEqual(levelAverages(root), brute(root)) } })
band.test.ts
✔ edge cases (2.0856ms) ✔ matches the depth-keyed totals on random trees (13.9634ms) ℹ tests 2 ℹ pass 2 ℹ fail 0
Output of one run; the millisecond figures vary
The edge cases are the empty tree, a single negative value, a fractional value, which is rejected, and a level whose total passes the limit, which is rejected as well. Related on LeetCode: Average of Levels in Binary Tree.
Why does the code compute the size of each level before processing it?
Part 5 · A symmetric layout
The problem
A designer lays out shelves as a tree and wants the layout to be symmetric: the left half should be the mirror image of the right half, in both shape and values. Decide whether a given tree is its own mirror.
Looking at the tree level by level gives a hint. In a symmetric tree each level reads the same forwards and backwards, but that is not enough on its own, because two trees can have palindromic levels and still differ in shape. The test has to compare nodes, not just values, so the shape counts.
The method is to compare pairs of nodes that must mirror each other. The root's left and right children are the first pair. For a pair to match, either both are missing, or both exist with equal values. Then their children pair up crosswise: the outer children together, and the inner children together. Keep the pairs in a queue and check them in turn.
// True when the tree is its own mirror image. A queue of pairs: the two // nodes in a pair must hold the same value, and their children pair up // outside-with-outside and inside-with-inside. export function isSymmetric(root: TreeNode | null): boolean { if (root === null) return true type Pair = [TreeNode | null, TreeNode | null] const queue: Pair[] = [[root.left, root.right]] for (let head = 0; head < queue.length; head++) { const [a, b] = queue[head] if (a === null && b === null) continue if (a === null || b === null || a.val !== b.val) return false queue.push([a.left, b.right], [a.right, b.left]) } return true }
sym.ts: a queue of pairs
The queue of pairs never holds more than about two levels of pairs. Every node except the root appears in at most one pair, so the whole test takes time proportional to the number of nodes.
A pair with one node missing is an immediate failure, since shapes differ. A pair of two missing nodes is fine and adds nothing. A pair of equal values adds two more pairs: the left node's left child with the right node's right child, and the left node's right child with the right node's left child.
A near miss
// Two shelf layouts. Both have the same values on the same levels. const mirror = fromLevels([4, 6, 6, 1, null, null, 1]) const nearly = fromLevels([4, 6, 6, 1, null, 1]) console.log('mirror layout:', isSymmetric(mirror)) console.log('near miss: ', isSymmetric(nearly))
Two layouts with the same values on the same levels
mirror layout: true near miss: false
Output of one run
Both layouts have 4 on top, two 6s below, and a 1 on each side of the third level, so each level reads the same from both ends. In the first, the left 6 holds its 1 on the left and the right 6 holds its 1 on the right, which mirrors. In the second both 6s hold their 1 on the left, so the two sides are copies of each other and not mirrors, and the check reports false.
This is why pairs are compared crosswise. Comparing the left side to the right side directly would call the second layout symmetric, because the two sides are equal. Mirrors need the outer children paired with each other and the inner children paired with each other.
An empty tree and a single node are symmetric, since nothing is left to contradict. A root with one child is not.
The same pairing idea is also natural as recursion: two nodes mirror each other when their values match and their children mirror crosswise. It is shorter, and it is checked against the queue version in the tests.
// The same test by recursion: two nodes mirror each other when their // values match and their children mirror crosswise. export function isSymmetricRec(root: TreeNode | null): boolean { const mirror = (a: TreeNode | null, b: TreeNode | null): boolean => { if (a === null || b === null) return a === b if (a.val !== b.val) return false return mirror(a.left, b.right) && mirror(a.right, b.left) } return root === null || mirror(root.left, root.right) }
sym.ts: the same test by recursion
Checking with a mirrored copy
The check makes a new tree with left and right swapped everywhere, and compares its level-order list with the original's. A tree is its own mirror exactly when the two lists are equal. The tests also build trees that are symmetric by construction, by joining a random tree to a mirrored copy of itself under a new root, so that enough symmetric cases are present.
// A fresh copy of the tree with left and right swapped everywhere. function mirrored(n: TreeNode | null): TreeNode | null { if (n === null) return null return new TreeNode(n.val, mirrored(n.right), mirrored(n.left)) } const check = (xs: (number | null)[]) => isSymmetric(fromLevels(xs))
A freshly mirrored copy of a tree
test('edge cases', () => { assert.equal(isSymmetric(null), true) assert.equal(isSymmetric(new TreeNode(1)), true) assert.equal(check([6, 2]), false) assert.equal(check([6, 2, 2]), true) assert.equal(check([6, 2, 2, 9, null, null, 9]), true) assert.equal(check([6, 2, 2, null, 9, 9]), true) // Same values, but the inner pair does not mirror. assert.equal(check([6, 2, 2, 9, null, 9]), false) assert.equal(check([6, 2, 2, null, 9, null, 9, 4]), false) }) test('agrees with comparing a tree to its mirrored copy', () => { const rand = mulberry32(85) let symmetric = 0 for (let t = 0; t < 3000; t++) { let root = randomTree(rand, Math.floor(rand() * 8), 2) if (rand() < 0.5 && root !== null) { // Build a tree that is symmetric by construction. root = new TreeNode(root.val, root, mirrored(root)) } const same = JSON.stringify(toLevels(root)) === JSON.stringify(toLevels(mirrored(root))) assert.equal(isSymmetric(root), same) assert.equal(isSymmetricRec(root), same) if (same) symmetric++ } assert.ok(symmetric > 500) })
sym.test.ts
✔ edge cases (1.4634ms) ✔ agrees with comparing a tree to its mirrored copy (14.1713ms) ℹ tests 2 ℹ pass 2 ℹ fail 0
Output of one run; the millisecond figures vary
The edge cases include trees whose levels are palindromes but whose shape is wrong. The count check at the end confirms that a good share of the random trees were symmetric, so the comparison is not trivially true or false. Related on LeetCode: Symmetric Tree.
Which children are paired when two nodes have equal values?
- The left node's left child with the right node's right child, and the left node's right child with the right node's left child.
Part 6 · Linking each level left to right
The problem
Each node of a tree gets one more pointer, next, meant to point at the node to its right on the same level, or at nothing for the last node of a level. With those pointers a level can be walked like a linked list, without a queue.
// A tree node with one more pointer, to its right neighbour. export class LinkedNode { val: number left: LinkedNode | null right: LinkedNode | null next: LinkedNode | null constructor(val: number) { this.val = val this.left = null this.right = null this.next = null } } // A copy of an ordinary tree made of LinkedNode objects. export function toLinked(n: TreeNode | null): LinkedNode | null { if (n === null) return null const copy = new LinkedNode(n.val) copy.left = toLinked(n.left) copy.right = toLinked(n.right) return copy }
next.ts: a node with a next pointer, and a copy helper
The queue method links each node to the one behind it in the queue, unless it is the last of its level. Because the snapshot says how many nodes are on the level, the index i tells when a node is last, and its next is the node now at the head of the queue.
// Links every node to the next node on its level, using a queue. export function linkWithQueue(root: LinkedNode | null) { if (root === null) return root const queue: LinkedNode[] = [root] let head = 0 while (head < queue.length) { const size = queue.length - head for (let i = 0; i < size; i++) { const n = queue[head++] n.next = i < size - 1 ? queue[head] : null if (n.left !== null) queue.push(n.left) if (n.right !== null) queue.push(n.right) } } return root }
next.ts: link with a queue
The queue holds up to a full level, so the extra memory grows with the widest level.
Using the links already made
The next pointers of one level can do the work of the queue for the level below. Once every node of level k is linked, you can walk that level from its first node through next. While walking it, you meet the children of each node in left-to-right order, which is exactly the order of level k + 1. Chain them together as you meet them.
A small trick avoids special cases: a dummy node at the head of the new chain. Every child is attached after a tail pointer, which starts at the dummy. When the walk ends, dummy.next is the first node of the next level, and the loop moves down.
// The same links with no queue. Each finished level is a linked list, // and walking it links the children, which form the level below. export function linkInPlace(root: LinkedNode | null) { let start = root while (start !== null) { const dummy = new LinkedNode(0) // head of the next level's list let tail = dummy for (let n: LinkedNode | null = start; n !== null; n = n.next) { if (n.left !== null) { tail.next = n.left tail = n.left } if (n.right !== null) { tail.next = n.right tail = n.right } } start = dummy.next } return root }
next.ts: link each level by walking the one above
This needs only a few variables, so the extra memory is constant. It works for trees of any shape, not only full ones, because it attaches whichever children exist.
Each node is attached once, as the child of the node above it, and each is visited once while its own level is walked. The time is proportional to the number of nodes. The one thing the method relies on is that the level above is already fully linked before you start on it, which the outer loop guarantees by finishing a level before moving down.
| Term | Meaning |
|---|---|
| next pointer | a field on each node that points to its right neighbour on the same level |
| dummy node | a placeholder at the front of a list so the first real item needs no special case |
Running and checking
// A lopsided building tree: not every level is full. const tree = fromLevels([1, 2, 3, 4, null, null, 5, 6]) const root = linkInPlace(toLinked(tree)) // Walk each level through its next pointers from its first node. let first: LinkedNode | null = root while (first !== null) { const row: number[] = [] let nextFirst: LinkedNode | null = null for (let n: LinkedNode | null = first; n !== null; n = n.next) { row.push(n.val) nextFirst ??= n.left ?? n.right } console.log(row.join(' -> '), '-> end') first = nextFirst }
Walking each level of a lopsided tree through its links
1 -> end 2 -> 3 -> end 4 -> 5 -> end 6 -> end
Output of one run
The tree has levels 1; 2 and 3; 4 and 5; and 6. Node 3 has only a right child, 5, and node 4 has the left child 6. The links chain 4 to 5 even though they have different parents.
The check does not read the next pointers to find levels. It lists the nodes of each level by expanding children, then requires every node to point at the next node of its level and the last one at null. Both versions are checked on 2,000 random trees.
// Nodes level by level, found without using any next pointer. function levelsOfNodes(root: LinkedNode | null): LinkedNode[][] { const out: LinkedNode[][] = [] let level = root === null ? [] : [root] while (level.length > 0) { out.push(level) level = level .flatMap((n) => [n.left, n.right]) .filter((c) => c !== null) } return out } // Every node points at its right neighbour; the last one at null. function linked(root: LinkedNode | null): boolean { return levelsOfNodes(root).every((level) => level.every((n, i) => n.next === (level[i + 1] ?? null)), ) }
A pointer check that ignores next while finding levels
test('edge cases', () => { assert.equal(linkWithQueue(null), null) assert.equal(linkInPlace(null), null) const lone = new LinkedNode(1) linkInPlace(lone) assert.equal(lone.next, null) }) test('both versions link every level, on random trees', () => { const rand = mulberry32(86) for (let t = 0; t < 2000; t++) { const plain = randomTree(rand, Math.floor(rand() * 25)) const a = linkWithQueue(toLinked(plain)) const b = linkInPlace(toLinked(plain)) assert.ok(linked(a)) assert.ok(linked(b)) } const full = toLinked(fromLevels([9, 4, 7, 2, 5, 6, 8])) assert.ok(linked(linkInPlace(full))) })
next.test.ts
✔ edge cases (1.084ms) ✔ both versions link every level, on random trees (27.682ms) ℹ tests 2 ℹ pass 2 ℹ fail 0
Output of one run; the millisecond figures vary
All chapters · Previous: Tree Depth-First Search: Recursion That Returns Answers Upward