Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Medium · Free

What is a BST? Search, insert, delete at interview level.

FresherFundamentalsData Structures & Algorithms
Model answer

Binary search tree

Left < root < right. Search/insert walk from root O(h); delete has three cases (leaf, one child, two children).

java
TreeNode insert(TreeNode root, int key) {
  if (root == null) return new TreeNode(key);
  if (key < root.val) root.left = insert(root.left, key);
  else if (key > root.val) root.right = insert(root.right, key);
  return root;
}
Balanced BST (AVL/Red-Black) keeps h = O(log n)—unbalanced degrades to O(n).