Skip to the solution
EasyDSA15 min read

What is a binary search tree (BST)?

675 views

The problem

Question presented to candidate: "Explain what a binary search tree is. Then, in Python, show me how search, insert and delete work, and tell me what their running time depends on."

What a strong answer should cover:

  • The BST property: every key in a node's left subtree is smaller, every key in its right subtree is larger โ€” for the whole subtree, not just the children.
  • Search, insert and delete each walk one root-to-leaf path, so they cost O(h), where h is the height.
  • The three delete cases (leaf, one child, two children) and the in-order successor.
  • In-order traversal visits the keys in sorted order.
  • Height is the whole story: about log2(n) when balanced, n โˆ’ 1 when keys arrive sorted; self-balancing trees (AVL, red-black) keep it O(log n).
  • Python specifics: there is no BST in the standard library (dict is a hash table, bisect works on a sorted list), and a recursive insert on sorted keys hits the default recursion limit of 1000.

Code / implementation expected: Optional โ€” a small Node class with insert, search and delete in Python 3.

  • trees
  • bst

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

15 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonBST basics: insert, search, delete (3 cases), in-order
PythonShape experiment: sorted vs shuffled vs balanced (1,023 keys)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 22 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you compute the GCD of two numbers?

Continue