All questions
Showing of 75What 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 above it.
Parent and child describe a direct link: the node above is the parent, the nodes hanging off it are its children. A leaf is any node with no children, sitting at the bottom of a branch. Internal nodes have at least one child.
You reach every other node by following edges down from the root. Trees model anything with nested containment: file systems, HTML documents, org charts, and menus. The shape lets you narrow a search quickly, since each step down commits to one branch and drops the rest. That branching 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; the root has depth zero. Height counts edges on the longest path from a node down to a leaf; 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: search and insert run in time proportional to height.
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. The practical point is that a short height means fast operations. When people say a tree is O(log n), they mean its height stays near log n rather than growing linearly.
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 sounds small but changes how you store and walk the structure. Each node needs just two child pointers, and left versus right becomes meaningful, not just a set of children. 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. Most fast lookup and priority structures build on the binary form for that reason.
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 -
Traversal means visiting every node in some defined order. The first three are depth-first and differ only by when you handle the current node relative to its children.
- Pre-order: node first, then left subtree, then right. Good for copying a tree or writing a prefix expression.
- In-order: left, node, right. On a binary search tree this yields sorted values.
- Post-order: left, right, then node. Good for deleting a tree or evaluating results bottom-up.
Level-order is different: it visits nodes row by row from the top down, using a queue. That answers questions about distance from the root, like the shallowest level where something appears.
All four touch every node once, so each costs O(n). The choice is about order, not speed. Pick the one whose visit timing matches what you need to compute.
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. The ordering rule is the invariant every node must obey.
For any node, all values in its left subtree are smaller, and all values in its right subtree are larger. This must hold for every node, not just direct children. That last part trips people up: a value deep in the left subtree still must stay below the ancestor it descends from.
This invariant is what makes searching 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 silently 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; if 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 -
Inserting reuses the same search path, then attaches the new value where the 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 automatically, since you followed it on the way down.
The cost mirrors search: proportional to height, so O(log n) on a balanced tree and O(n) on a skewed one. Duplicates need a rule decided up front, like sending equals right or bumping a count on the existing node. One catch: inserting already-sorted values builds a long one-sided chain. Without rebalancing, the tree becomes a slow 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, recursively. Pair that order with the BST invariant and sorted output falls out naturally.
The invariant guarantees everything left of a node is smaller and everything right is larger. So by fully processing the left subtree before touching the node, you emit all smaller values first. Then the node, then all larger values from the right subtree. Apply that reasoning at every level and 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, the invariant is violated somewhere.
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).
The danger is real with ordered input. Inserting sorted values into a plain BST builds a one-sided line, and it silently behaves like a linked list. Self-balancing trees fix this by adjusting shape as you insert and delete, trading a little bookkeeping for a height guarantee. That guarantee is what lets you promise fast lookups regardless of the order 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 that maintains a simple ordering between parents and children. Two properties define it together, and both must hold at all times.
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 you store it 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 to each other, so the heap is far weaker than a sorted order. That weakness is the point: it makes reading the top element 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; 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. Want the cheapest task next? Min-heap. Want the highest-scoring item? Max-heap. Peeking the top costs O(1); removing it costs O(log n) either way.
A common trick: if your library only ships one kind, negate the keys to fake the other. That saves writing a second comparator and avoids subtle sign bugs.
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?
How do you delete a node with two children from a BST?
How do you find the minimum and maximum values in 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?
What do self-balancing rotations accomplish, without the exact mechanics?
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?
What distinguishes complete, full, and perfect binary trees?
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?
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?
At a billion keys, why does a B-tree beat an in-memory balanced BST?
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 do you break ties or keep FIFO order among equal priorities?
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.
64 of 75 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.