skip to content

Trees

Hierarchical structures are the interview's favorite recursion playground: I learn binary-tree anatomy and traversals, the BST invariant and how it breaks down, why libraries reach for self-balancing trees, and the specialist trees (tries, B-trees, segment trees) that power search engines, databases, and range queries. Interviewers use trees to test whether I can reason recursively and pick the right structure for ordered or prefix-shaped data.

part ofData structures & algorithmsoverview, primer and where to startread it →
on this pageshow

explore

questions

page 2 of 2

In a B+-tree, why do records live only in the linked leaf level?

level: middleimportance: should knowfreq 54%

basics

~20 s

Keeping records out of interior nodes lets each interior page hold only separator keys and pointers, raising fanout and lowering height. Linking the leaves turns a range scan into one descent plus a sequential walk instead of a tree traversal.

open as a page

In a Fenwick tree, why does stripping index i's lowest set bit walk exactly one prefix?

level: middleimportance: should knowfreq 38%

basics

~20 s

In a Fenwick tree, node i aggregates the lowbit(i) positions ending at i. Stripping that low bit lands on the last position the node did not cover, so successive nodes tile the prefix with no gap and no overlap.

open as a page

In a suffix array over one long sequencing read, how does the LCP array expose the longest repeated segment?

level: middleimportance: should knowfreq 30%

basics

~20 s

The LCP array records how many leading characters each adjacent pair of lexicographically sorted suffixes shares. The largest entry is the length of the longest segment occurring at least twice, and the offset beside it says where that segment starts.

open as a page

What does a suffix array actually store, and why is its space O(n) rather than O(n^2)?

level: middleimportance: should knowfreq 40%

basics

~20 s

A suffix array holds n integers: the starting positions of a text's n suffixes, sorted in lexicographic order. The suffixes themselves are never copied — each is read from the original text — so the space stays O(n).

open as a page

When does a trie use more memory than a hash set holding the same keys?

level: middleimportance: should knowfreq 50%

basics

~20 s

A trie saves memory only when keys share long prefixes. For long, mostly distinct keys it allocates about one node per symbol, each with child links and a marker — usually far more than storing the keys whole in a hash set.

open as a page

A tree-diameter function calls a separate height routine at every node — what is its true time complexity?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Worst case O(n^2): each node's height is recomputed once per ancestor, so a chain-shaped tree pays the sum of all depths. A balanced tree costs O(n log n). Fusing both walks into one post-order pass restores O(n).

open as a page

A bounds-based search-tree validator rejects a valid tree holding the most negative key — why?

level: seniorimportance: should knowfreq 38%

basics

~20 s

The recursion seeded its initial bounds with the key type's extreme representable values, so a real key equal to that extreme is indistinguishable from being out of range. Make the bounds optional and skip absent comparisons, or use a bound type wider than the key type.

open as a page

Is AVL's strict balancing worth its rotation cost for a calibration table read thousands of times per write?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Usually yes: the strict invariant charges constant restructuring per write and buys a worst-case height near 1.44·log2(n) on every read, so at a thousand reads per write the shorter search paths dominate. Confirm by measuring at production size.

open as a page

Why choose a red-black tree over an AVL tree for an index under heavy insert-delete churn?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Red-black trees pay less per write: at most two rotations per insertion, three per deletion, and the common repair changes colors only. AVL rebalancing after a deletion can rotate all the way to the root. AVL's tighter height wins when reads dominate.

open as a page

Recursive traversal of a deep rule tree overflows the call stack — what changes when you rewrite it with an explicit stack?

level: seniorimportance: should knowfreq 54%

basics

~20 s

You take over the bookkeeping recursion did for you. An explicit stack holds pending nodes, and children are pushed in reverse so the left pops first. Preorder converts mechanically; postorder needs extra state to know both children finished.

open as a page

A nightly import inserts sorted SKU IDs into a plain binary search tree — what do you flag in review?

level: seniorimportance: should knowfreq 47%

basics

~20 s

Flag that the arrival order is sorted: every key lands to the right of the previous one, so the index becomes a chain of length n. Lookups degrade from O(log n) to O(n), and the import loop itself costs Θ(n²).

open as a page

In a binary search tree of price levels, how do you find the largest key at or below X when X is absent?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Carry a candidate down the ordinary search descent: when the current key is below X, record it and step right; when it is above X, step left. The last recorded key is the largest at or below X.

open as a page

Why can a Fenwick tree answer arbitrary range sums but not arbitrary range minima?

level: seniorimportance: should knowfreq 36%

basics

~20 s

A Fenwick tree answers a general range by subtracting prefixes, which requires an invertible aggregate. Minimum has no inverse — two prefix minima say nothing about the range between them — so range minima need a structure that combines covering blocks.

open as a page

Why can't a single hash lookup answer a longest-prefix-match routing query?

level: seniorimportance: should knowfreq 40%

basics

~20 s

A hash structure answers exact-key membership only, and a destination address is almost never itself a stored entry. Longest-prefix match asks which stored prefix of any length matches deepest — that needs an ordered descent, not one lookup.

open as a page

Is a suffix array worth its memory for thousands of substring queries over a fixed 10^8-character archive?

level: principalimportance: should knowfreq 26%

basics

~20 s

Usually yes: past a few dozen queries the one-time build amortises, while a per-query scan never stops costing. Decide on resident memory — roughly four bytes per character plus the archive — how often the archive changes, and who will own the index.

open as a page

An autocomplete trie sized for ASCII blows its memory ceiling on a multilingual catalog — how do you decide what to change?

level: principalimportance: should knowfreq 30%

basics

~20 s

Measure first: node count, fanout and bytes per node. The usual culprit is a child slot reserved per possible symbol — fine for a tiny alphabet, impossible for a universal one. The levers: children representation, compression, byte indexing, or no trie at all.

open as a page

In a red-black tree insert fixup, what decides whether you recolor or rotate?

level: middleimportance: nice to knowfreq 32%

basics

~20 s

The uncle's color decides. In a red-black tree insert fixup, a red uncle means recolor parent, uncle and grandparent and push the violation two levels up; a black or absent uncle means one or two rotations end the repair immediately.

open as a page

In left-child right-sibling encoding, what does preorder on the encoded binary tree correspond to?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

It corresponds exactly to preorder on the original n-ary tree. Left-child right-sibling gives every node two fixed pointers, first child and next sibling, and a preorder walk of that binary shape emits the original nodes in the original order.

open as a page

In a comment tree, a nesting cap rejects a reply whose height exceeds five; why does it never fire?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

A newly posted reply is always a leaf, so its height is zero no matter how deeply it sits. The rule needs depth, the distance from the thread root, which is the parent's depth plus one and is known at insertion.

open as a page

If a B-tree index fits entirely in RAM, does its high fanout still pay off?

level: seniorimportance: nice to knowfreq 34%

basics

~20 s

Not at the same node size. High fanout was never valuable in itself — it matched node size to the storage transfer unit. In memory that unit shrinks from a page to a cache line, so the right node holds tens of keys, not hundreds.

open as a page

A suffix tree answers substring queries in O(m); why do practitioners ship a suffix array instead?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

Suffix arrays win on constants, not asymptotics. A suffix tree costs roughly ten to twenty bytes per character in nodes and pointers; a suffix array is one integer per position, is far friendlier to caches, and with an LCP array it answers most of the same queries.

open as a page

When does a preprocessed lowest-common-ancestor index beat a per-query walk on a large, changing tree?

level: principalimportance: nice to knowfreq 28%

basics

~20 s

When queries are frequent, the tree is deep, and mutations are rare or append-only. An index buys O(log n) queries for O(n log n) build time and memory, and re-parenting invalidates it. On a shallow or churning tree the walk wins.

open as a page

When replicating a decision tree between services, when must the serialization preserve its exact shape?

level: principalimportance: nice to knowfreq 30%

basics

~20 s

Preserve the shape whenever the shape is semantic: evaluation order, branch identity, per-node metadata, or paths that appear in audit records. When the tree is merely an ordered index over keys, ship the keys in order and let the receiver rebuild — smaller, self-checkable and far more tolerant of version skew.

open as a page

A shared plain binary search tree index serves several services, some feeding it monotone keys — what is your call?

level: principalimportance: nice to knowfreq 33%

basics

~10 s

Put the guarantee in the structure, not in caller discipline: a shared index whose inputs you do not control should maintain its own height bound. Caller-side fixes fit only small, bounded, cold indexes.

open as a page

Fenwick or segment tree for a shared metrics library — how do you decide, and what do you tell the team?

level: principalimportance: nice to knowfreq 24%

basics

~10 s

Decide from the aggregate and the workload, not from elegance: the compact prefix-based structure fits only invertible aggregates, a segment tree fits any associative one, and batched writes justify neither.

open as a page

showing 31–55 of 55