Practise Trees, BSTs & Heaps one question at a time. Answer out loud or in writing, get graded, and see exactly what you missed.
What is a tree, and what do root, parent, child, and leaf mean?
A tree is a hierarchical structure of nodes connected by edges, with no cycles. Each node holds a value and links to nodes below it. One node sits at the top as the root, the single entry point with no parent.
Parent and child describe a direct link. The node above is the parent, and the nodes hanging off it are its children. A leaf is any node with no children. Internal nodes have at least one child.
You reach every other node by following edges down from the root. Trees model nested containment, such as file systems, HTML documents and org charts. Each step down a search commits to one branch and drops the rest, which is why trees beat flat lists for hierarchical data.
Missed:
“So all four visit every node, they just differ in the order. The first three are depth-first. Pre-order handles the node before its children, so root, then left, then right, and I'd use that one to copy a tree. In-order is left, root, right, and on a binary search tree that gives you the values back in sorted order. Post-order does both children first and the node last, which is what you want when you're freeing a tree, because you can't delete a parent before its kids. Level-order is the breadth-first one: you push the root onto a queue and go level by level.”
Knew itThey have the three orders and level-order right, with correct use cases for pre, in, and post. They skip mentioning that all traversals cost O(n) and never frame the choice as about order rather than speed.
Missed: Didn't mention level-order's typical use case, like finding distance from the root
Missed: Didn't note all four traversals are O(n) and that the choice is about order, not speed
Get your own answers graded
Sign up free. Your account comes with 50 credits for grading, and it remembers what you missed.
What it covers
- Tree basics and terminology
- Traversals and tree algorithms
- BST invariant and operations
- Balance and self-balancing trees
- Heap structure and operations
- Priority queues and heap patterns
- Tries and string keys
- Ordered queries and augmented trees
- Advanced priority queue designs
- B-trees and hardware performance
- Concurrent and persistent structures
All 76 questions
Tree basics and terminology
What a tree is, how it differs from a graph, root, parent, child, leaf, height and depth, and the binary tree shapes: complete, full and perfect.
- What is a tree, and what do root, parent, child, and leaf mean?
- What is the difference between a node's height and its depth?
- What is a binary tree, and how does it differ from a general tree?
- What is the difference between a tree and a graph? Pro
- What distinguishes complete, full, and perfect binary trees? Pro
Traversals and tree algorithms
Depth-first and level-order traversals, their stack and memory costs, Morris traversal, serialization, lowest common ancestor and balance checks.
- What are pre-order, in-order, post-order, and level-order tree traversals?
- Why can a recursive traversal overflow the stack on a skewed tree? Pro
- Why can level-order traversal use far more memory than in-order? Pro
- How do you find the lowest common ancestor of two nodes? Pro
- How do you check whether a binary tree is height-balanced? Pro
- How do you serialize and deserialize a binary tree? Pro
- How can you traverse a binary tree using O(1) extra space? Pro
BST invariant and operations
The binary search tree ordering rule and how search, insert, delete, min and max, successor, sorted in-order output and validation work.
- What is a binary search tree, and what invariant must every node satisfy?
- How do you search for a value in a BST, and what does it cost?
- How do you insert a new value into a binary search tree?
- Why does an in-order traversal of a BST produce sorted output?
- How do you find the minimum and maximum values in a BST? Pro
- How do you delete a node with two children from a BST? Pro
- How do you find the in-order successor of a node in a BST? Pro
- What is the classic bug when checking whether a tree is a valid BST? Pro
Balance and self-balancing trees
Why height matters, how input order degrades a BST, and how AVL, red-black trees, treaps, rotations and rebuilds keep it balanced.
- What does it mean for a tree to be balanced, and why does it matter?
- What input order makes a BST degrade to linear-time operations? Pro
- How do AVL trees and red-black trees differ in their tradeoffs? Pro
- At a high level, what do rotations do in a self-balancing tree? Pro
- Why can the same keys form many different BSTs, and which is best? Pro
- What rules does a red-black tree enforce, and how do they keep it balanced? Pro
- How would you rebuild a degenerate BST into a balanced one? Pro
- What is a treap, and how does randomized priority keep it balanced? Pro
Heap structure and operations
The binary heap's shape and order rules, array storage, sift up and down, building in O(n), and what a heap can and cannot find quickly.
- What is a binary heap, and what shape and ordering properties define it?
- What is the difference between a min-heap and a max-heap?
- How is a binary heap stored in an array without any pointers? Pro
- How do you insert into a binary heap, and why is it O(log n)? Pro
- How do you remove the top element from a binary heap? Pro
- Why must a binary heap be a complete binary tree, and what does that buy? Pro
- Why is building a heap O(n) rather than O(n log n)? Pro
- Why can't you efficiently search a heap for an arbitrary value? Pro
- In a min-heap, why is the minimum O(1) but the maximum O(n)? Pro
- How do you get max-heap behavior from a min-heap by negating keys? Pro
Priority queues and heap patterns
Priority queue operations and the classic heap uses: top K, running median, K-way merge, Dijkstra, tie-breaking, timers and heapsort.
- What is a priority queue, and what core operations does it support? Pro
- When should you reach for a heap instead of a sorted list? Pro
- How does heapsort sort an array in place using a heap? Pro
- How do you keep the K largest items of a stream, and which heap? Pro
- Why does Dijkstra's shortest-path algorithm rely on a priority queue? Pro
- How do you find the running median of a stream using two heaps? Pro
- How do you merge K sorted lists efficiently with a heap? Pro
- How do you break ties or keep FIFO order among equal priorities? Pro
- How would you find the top K across a billion distributed records? Pro
- How would you design a timer or scheduler around a heap? Pro
- Why is heapsort seldom used despite its worst-case O(n log n) guarantee? Pro
Tries and string keys
How tries store strings by shared prefix, their memory cost, how they compare with hash maps, radix trees and autocomplete at scale.
- What is a trie, and what kind of lookups is it good at? Pro
- How much memory does a trie cost, and when is that a problem? Pro
- How does a trie compare with a hash map for string keys? Pro
- What is a radix tree, and how does it shrink a trie's memory? Pro
- How would you build autocomplete over millions of terms with a trie? Pro
Ordered queries and augmented trees
What ordered trees answer that hash tables cannot: range queries, kth-smallest with subtree sizes, interval trees and segment trees.
- What ordered operations does a BST support that a hash table cannot? Pro
- When is a hash table a better choice than a BST? Pro
- How do you augment a BST to answer kth-smallest queries in O(log n)? Pro
- How do you support fast range queries over a large ordered set? Pro
- How does an interval tree find all intervals overlapping a query? Pro
- How does a segment tree answer range-sum or range-min queries quickly? Pro
Advanced priority queue designs
Beyond the binary heap: indexed and lazy-deletion queues, d-ary, mergeable and Fibonacci heaps, bucket queues, BST-backed and external queues.
- When does a balanced BST beat a heap as a priority queue? Pro
- When does a d-ary heap beat a binary heap on cache? Pro
- How do you handle stale entries when a heap can't decrease-key? Pro
- What do mergeable heaps do that a binary heap cannot? Pro
- When is a Fibonacci heap worth it for Dijkstra, and why rarely? Pro
- How do you run a priority queue larger than memory? Pro
- How does an indexed priority queue let you change an element's priority? Pro
- When does a bucket or calendar queue outperform a binary heap? Pro
B-trees and hardware performance
Why storage engines use B-trees and B+ trees, how pointer-chasing misses the CPU cache, and how write-heavy loads stress balanced trees.
Concurrent and persistent structures
Making trees and priority queues safe under many threads, skip lists as a concurrent alternative, and persistent trees through copy-on-write.
All questions
Showing of 76What is a tree, and what do root, parent, child, and leaf mean?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
A tree is a hierarchical structure of nodes connected by edges, with no cycles. Each node holds a value and links to nodes below it. One node sits at the top as the root, the single entry point with no parent.
Parent and child describe a direct link. The node above is the parent, and the nodes hanging off it are its children. A leaf is any node with no children. Internal nodes have at least one child.
You reach every other node by following edges down from the root. Trees model nested containment, such as file systems, HTML documents and org charts. Each step down a search commits to one branch and drops the rest, which is why trees beat flat lists for hierarchical data.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
What is the difference between a node's height and its depth?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
Depth counts edges from the root down to a node, so the root has depth zero. Height counts edges on the longest path from a node down to a leaf, so a leaf has height zero.
So depth looks upward toward the root, and height looks downward toward the deepest descendant. The whole tree's height equals the root's height, which is the longest root-to-leaf path. That number drives cost, because search and insert run in time proportional to height.
A short height means fast operations. When people say a tree is O(log n), they mean its height stays near log n instead of growing linearly.
A common mix-up is swapping the two or counting nodes instead of edges. Some texts count nodes, making both values larger by one, so always confirm the convention.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
What is a binary tree, and how does it differ from a general tree?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
A binary tree limits each node to at most two children, usually named left and right. A general tree lets a node have any number of children, with no fixed slots.
That cap changes how you store and walk the structure. Each node needs just two child pointers, and left versus right becomes meaningful. This ordering is what later lets binary search trees and heaps assign meaning to sides.
An empty spot matters too. A node can have a left child but no right, and that gap is part of the shape.
General trees suit data with variable fan-out, like a folder holding any number of files. Binary trees suit ordered decisions, where each step picks one of two directions, and most fast lookup and priority structures build on that form.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
What are pre-order, in-order, post-order, and level-order tree traversals?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
They are four ways to visit every node of a tree in a defined order. The first three are depth-first and differ only by when you handle the current node relative to its children.
- Pre-order visits the node, then the left subtree, then the right. It suits copying a tree or writing a prefix expression.
- In-order visits left, node, right, which yields sorted values on a binary search tree.
- Post-order visits left, right, then the node. It suits deleting a tree or evaluating results bottom-up.
Level-order is the breadth-first one, visiting nodes row by row from the top with a queue. It suits questions about distance from the root.
All four touch every node once, so each costs O(n). The choice is about order, not speed.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
What is a binary search tree, and what invariant must every node satisfy?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
A binary search tree is a binary tree that keeps its values ordered for fast lookup. Its invariant is that for any node, all values in its left subtree are smaller and all values in its right subtree are larger.
The rule covers whole subtrees, not just direct children, so a value deep in the left subtree must stay below the ancestor it descends from.
The invariant makes search cheap. At each node you compare, then discard a whole subtree and follow the other side. Duplicates need a chosen policy, such as always going right or storing a count. Keep the invariant true on every insert and delete, and lookups stay logarithmic on a balanced tree. Break it anywhere and searches can miss values that are present.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
How do you search for a value in a BST, and what does it cost?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
Searching starts at the root and compares your target to the current node. If they match, you are done. If the target is smaller, go left, and if it is larger, go right. Repeat until you find it or fall off the tree into an empty spot, which means absent.
Each step throws away one subtree, so you follow a single root-to-leaf path. That means the cost is proportional to the tree's height, not its node count.
while (node && node.val !== target)
node = target < node.val ? node.left : node.right;
// node is the match or null
On a balanced tree the height is about log n, so search runs in O(log n). On a lopsided tree that degrades toward O(n), since the path can be as long as the node count. That gap is exactly why balancing matters.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
How do you insert a new value into a binary search tree?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
Insertion follows the path a search for the value would take, then attaches the new value where that search would have failed. You walk down comparing, going left for smaller and right for larger, until you reach an empty child slot. You place the new node there as a leaf.
New values always land as leaves, so existing nodes never move. That keeps insertion simple and preserves the ordering invariant, since you followed it on the way down.
Duplicates need a rule decided up front, like sending equals right or bumping a count on the existing node.
The cost mirrors search. It is proportional to height, so O(log n) on a balanced tree and O(n) on a skewed one. Sorted input builds a long one-sided chain that every operation walks like a linked list, which is why real systems self-balance after inserts.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
Why does an in-order traversal of a BST produce sorted output?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
In-order traversal visits the left subtree, then the node, then the right subtree, and the BST invariant puts those three parts in ascending order. Everything in a node's left subtree is smaller than the node, and everything in its right subtree is larger. So the traversal emits all smaller values before the node and all larger values after it. The same holds at every level, so the whole sequence comes out ascending.
inorder(node.left);
visit(node.val);
inorder(node.right);
// prints values low to high
This gives you a free sorted listing in O(n) without any extra sorting step. It also means you can spot a broken tree cheaply. If an in-order pass ever emits a value smaller than the previous one, some node violates the invariant.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
What does it mean for a tree to be balanced, and why does it matter?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
Balanced means the tree's height stays close to the minimum for its node count, roughly log n. No branch is allowed to grow much longer than the others. Different schemes define the slack differently, but all cap how lopsided the shape can get.
Height matters because search, insert and delete all cost time proportional to it. A balanced tree keeps those at O(log n). An unbalanced one can stretch into a chain, dragging the same operations toward O(n).
Ordered input makes this real. Inserting sorted values into a plain BST builds a one-sided line that behaves like a linked list. Self-balancing trees adjust their shape as you insert and delete, trading a little bookkeeping for a height guarantee. That guarantee keeps lookups fast whatever order the data arrives in.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
What is a binary heap, and what shape and ordering properties define it?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
A binary heap is a complete binary tree with a simple ordering between parents and children. Two properties define it, and both must always hold.
The shape property says the tree is complete. Every level is full except possibly the last, which fills left to right. That compact shape lets it live in a plain array with no pointers.
The heap property is a parent-child rule. In a max-heap, every parent is at least as large as its children, so the largest value sits at the root. A min-heap flips it, keeping the smallest at the root. The rule only relates parents to their own children, not siblings, so a heap is far weaker than a sorted order. That weakness makes reading the top O(1) while keeping inserts cheap.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
What is the difference between a min-heap and a max-heap?
Answer it yourself first - out loud, or typed below.
How should your speech become text?
Listening… your words appear above as you speak - tap Stop when you're done.
Recording · cr - tap Stop & transcribe when you're done.
Transcribing with AI…
Voice:
Last attempt -
The only difference is which extreme sits at the root. A min-heap keeps its smallest value on top, and a max-heap keeps its largest. Both obey the same shape rule and the same parent-child ordering, just flipped.
In a min-heap, every parent is smaller than or equal to its children. In a max-heap, every parent is larger than or equal to its children. Neither orders siblings, so you cannot read a sorted list off the array.
You pick based on what you pull first. To take the cheapest task next, use a min-heap. To take the highest-scoring item, use a max-heap. Peeking at the top costs O(1), and removing it costs O(log n) either way.
If your library only ships one kind, negating numeric keys fakes the other.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
What is a priority queue, and what core operations does it support?
How is a binary heap stored in an array without any pointers?
How do you insert into a binary heap, and why is it O(log n)?
How do you remove the top element from a binary heap?
Why must a binary heap be a complete binary tree, and what does that buy?
What is a trie, and what kind of lookups is it good at?
When should you reach for a heap instead of a sorted list?
What is the difference between a tree and a graph?
How do you find the minimum and maximum values in a BST?
What distinguishes complete, full, and perfect binary trees?
How do you delete a node with two children from a BST?
How do you find the in-order successor of a node in a BST?
What input order makes a BST degrade to linear-time operations?
What is the classic bug when checking whether a tree is a valid BST?
How do AVL trees and red-black trees differ in their tradeoffs?
At a high level, what do rotations do in a self-balancing tree?
What ordered operations does a BST support that a hash table cannot?
When is a hash table a better choice than a BST?
Why can a recursive traversal overflow the stack on a skewed tree?
Why can level-order traversal use far more memory than in-order?
How do you find the lowest common ancestor of two nodes?
How much memory does a trie cost, and when is that a problem?
How does a trie compare with a hash map for string keys?
How do you check whether a binary tree is height-balanced?
Why can the same keys form many different BSTs, and which is best?
Why is building a heap O(n) rather than O(n log n)?
How does heapsort sort an array in place using a heap?
How do you keep the K largest items of a stream, and which heap?
Why does Dijkstra's shortest-path algorithm rely on a priority queue?
Why can't you efficiently search a heap for an arbitrary value?
How do you find the running median of a stream using two heaps?
How do you merge K sorted lists efficiently with a heap?
When does a balanced BST beat a heap as a priority queue?
In a min-heap, why is the minimum O(1) but the maximum O(n)?
How do you get max-heap behavior from a min-heap by negating keys?
What rules does a red-black tree enforce, and how do they keep it balanced?
How do you break ties or keep FIFO order among equal priorities?
How do you augment a BST to answer kth-smallest queries in O(log n)?
How do you support fast range queries over a large ordered set?
How does an interval tree find all intervals overlapping a query?
How does a segment tree answer range-sum or range-min queries quickly?
Why do databases and filesystems use B-trees instead of binary search trees?
How does a B+ tree differ from a B-tree for range scans?
How does pointer-chasing in a BST hurt CPU cache performance?
How would you rebuild a degenerate BST into a balanced one?
How do heavy write workloads stress a self-balancing tree?
How would you make a BST safe for concurrent readers and writers?
What is a persistent tree, and how does copy-on-write enable it?
How do you serialize and deserialize a binary tree?
How can you traverse a binary tree using O(1) extra space?
When would you prefer a skip list over a balanced BST?
What is a radix tree, and how does it shrink a trie's memory?
How would you build autocomplete over millions of terms with a trie?
What is a treap, and how does randomized priority keep it balanced?
When does a d-ary heap beat a binary heap on cache?
How do you handle stale entries when a heap can't decrease-key?
What do mergeable heaps do that a binary heap cannot?
When is a Fibonacci heap worth it for Dijkstra, and why rarely?
How would you make a priority queue safe under many concurrent threads?
How do you run a priority queue larger than memory?
How would you find the top K across a billion distributed records?
How would you design a timer or scheduler around a heap?
How does an indexed priority queue let you change an element's priority?
Why is heapsort seldom used despite its worst-case O(n log n) guarantee?
When does a bucket or calendar queue outperform a binary heap?
This answer is part of Pro.
The full written answer, with the trade-offs and follow-ups an interviewer will probe.
No matches
Try a different filter or search term.
Trees, BSTs & Heaps in pictures.
A quick recap of Trees, BSTs & Heaps in 32 short animated pictures, one idea at a time. About 8 min to get the whole topic back in your head before you walk in. Pause any picture, slow it down, or step through it.
Pro The first chapter is free to play. The other 30 pictures come with Pro.
This picture is part of Pro. The first chapter is free to play; the other 30 pictures come with Pro.
Get Pro · $10/mo Already Pro? Sign in65 of 76 Trees, BSTs & Heaps answers are in Pro.
Full answers, code samples, and AI explanations that go simpler or deeper. Cancel anytime.
- Full answers + code
- AI explanations, simpler or deeper
- 1,000 AI credits / month
- Cancel anytime
Change topic
Pick a different technology or stack. Your current topic stays put until you choose a new one.
MEAN
MongoDB, Express, Angular, Node.jsMERN
MongoDB, Express, React, Node.jsDjango
Python Full-Stack DevelopmentRuby on Rails
Convention over ConfigurationServerless on AWS
Serverless Architecture on AWSInterviewers also test these - they're common to every stack, whichever one you picked above.
Flutter Mobile
Flutter Cross-Platform Mobile DevelopmentInterviewers also test these - they're common to every stack, whichever one you picked above.
Spring Boot
Enterprise Java Development.NET
Microsoft EcosystemVue
Vue.js, Vite, TypeScript, Tailwind, Node.jsGo Backend
Golang, gRPC, PostgreSQL, Redis, RabbitMQInterviewers also test these - they're common to every stack, whichever one you picked above.
FastAPI
Python, FastAPI, SQLAlchemy, PostgreSQLReact Native
React, TypeScript, Redux, FirebaseiOS Native
Swift, SwiftUI, UIKit, FirebaseAndroid Native
Java, Jetpack Compose, FirebaseDevOps / Platform
Docker, Kubernetes, Terraform, CI/CDInterviewers also test these - they're common to every stack, whichever one you picked above.
AI Engineer
LLMs, RAG, Agents, EvalsAI-Powered Developer
Claude Code, Copilot, Agentic WorkflowsCore SWE Interview Prep
Data structures, algorithms, OS, concurrency, networking, gitInterviewers also test these - they're common to every stack, whichever one you picked above.
Interviewers also test these - they're common to every stack, whichever one you picked above.