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 pageshowhide
explore
- Binary Trees8 questions
- Terminology & Properties4 questions
- The Four Traversals4 questions
- Binary Search Trees8 questions
- BST Invariant & Operations4 questions
- Balance & Degeneration4 questions
- Self-Balancing Trees8 questions
- AVL Trees4 questions
- Red-Black Trees4 questions
- Tries (Prefix Trees)4 questions
- Suffix Trees & Arrays4 questions
- Disk & Range-Query Trees9 questions
- B-Trees & B+-Trees4 questions
- Segment Trees & Fenwick (BIT)5 questions
- General Tree Algorithms14 questions
- LCA, Diameter & Path Problems5 questions
- Serialization & Validation5 questions
- N-ary Trees4 questions
- Computer Scienceskillanchors this topic
- Data Structures & Algorithmsskillanchors this topic
- AI & Data Scientistrole
- AI Engineerrole
- AI Red Teamingrole
- Android Developerrole
- Backend Developerrole
- Blockchain Developerrole
- Cyber Security Expertrole
- Data Analystrole
- Data Engineerrole
- DevOps / SRE Engineerrole
- DevSecOps Engineerrole
- Forward Deployed Engineerrole
- Frontend Developerrole
- Full Stack Developerrole
- Game Developerrole
- Java Backend Developerrole
- Java SDETrole
- Kotlin Backend Developerrole
- MLOps Engineerrole
- Machine Learning Engineerrole
- Network Engineerrole
- PostgreSQL DBArole
- QA Engineerrole
- Software Architectrole
- iOS Developerrole
questions
page 2 of 2In a B+-tree, why do records live only in the linked leaf level?
basics
~20 sKeeping 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.
In a Fenwick tree, why does stripping index i's lowest set bit walk exactly one prefix?
basics
~20 sIn 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.
In a suffix array over one long sequencing read, how does the LCP array expose the longest repeated segment?
basics
~20 sThe 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.
What does a suffix array actually store, and why is its space O(n) rather than O(n^2)?
basics
~20 sA 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).
When does a trie use more memory than a hash set holding the same keys?
basics
~20 sA 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.
A tree-diameter function calls a separate height routine at every node — what is its true time complexity?
basics
~20 sWorst 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).
A bounds-based search-tree validator rejects a valid tree holding the most negative key — why?
basics
~20 sThe 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.
Is AVL's strict balancing worth its rotation cost for a calibration table read thousands of times per write?
basics
~20 sUsually 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.
Why choose a red-black tree over an AVL tree for an index under heavy insert-delete churn?
basics
~20 sRed-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.
Recursive traversal of a deep rule tree overflows the call stack — what changes when you rewrite it with an explicit stack?
basics
~20 sYou 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.
A nightly import inserts sorted SKU IDs into a plain binary search tree — what do you flag in review?
basics
~20 sFlag 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²).
In a binary search tree of price levels, how do you find the largest key at or below X when X is absent?
basics
~20 sCarry 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.
Why can a Fenwick tree answer arbitrary range sums but not arbitrary range minima?
basics
~20 sA 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.
Why can't a single hash lookup answer a longest-prefix-match routing query?
basics
~20 sA 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.
Is a suffix array worth its memory for thousands of substring queries over a fixed 10^8-character archive?
basics
~20 sUsually 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.
An autocomplete trie sized for ASCII blows its memory ceiling on a multilingual catalog — how do you decide what to change?
basics
~20 sMeasure 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.
In a red-black tree insert fixup, what decides whether you recolor or rotate?
basics
~20 sThe 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.
In left-child right-sibling encoding, what does preorder on the encoded binary tree correspond to?
basics
~20 sIt 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.
In a comment tree, a nesting cap rejects a reply whose height exceeds five; why does it never fire?
basics
~20 sA 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.
If a B-tree index fits entirely in RAM, does its high fanout still pay off?
basics
~20 sNot 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.
A suffix tree answers substring queries in O(m); why do practitioners ship a suffix array instead?
basics
~20 sSuffix 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.
When does a preprocessed lowest-common-ancestor index beat a per-query walk on a large, changing tree?
basics
~20 sWhen 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.
When replicating a decision tree between services, when must the serialization preserve its exact shape?
basics
~20 sPreserve 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.
showing 31–55 of 55