A2Z Lesson

Log in
← Back to the A2Z sheet

Step 14 Binary Search Trees — Theory and Basics

Introduction to BST

Easy

A binary search tree (BST) adds one ordering rule to a binary tree: for every node, all values in its left subtree are smaller and all values in its right subtree are larger. That single invariant turns blind O(n) searching into a guided walk that discards half the tree at each step — O(log n) on balanced shapes. This lesson covers the invariant, the three core operations (search, insert, delete), and why the inorder traversal of a BST is always sorted.

The BST invariant

For every node N: every value in N's left subtree is less than N's value, and every value in N's right subtree is greater. The condition is about entire subtrees, not just immediate children — a node can satisfy both children locally yet violate an ancestor's bound, which is exactly why validating a BST needs a (min, max) range passed down, not just parent-child checks.

Duplicates need a policy: most problem statements here assume distinct values; when duplicates exist, decide whether they go left or right and apply it consistently, since search and delete depend on it.

Search: a guided walk

Start at the root. If the target equals the node value, done. If it is smaller, the invariant guarantees it can only live in the left subtree; if larger, only in the right. Move down and repeat; falling off the tree (reaching None) means absent.

Each step discards one whole subtree, so the cost is O(h) where h is the height: O(log n) for balanced trees, O(n) for a skewed one — inserting sorted data into a plain BST builds exactly that worst case, which is why self-balancing variants (AVL, red-black) exist in libraries.

def search_bst(root, target): node = root while node is not None: if target == node.data: return node node = node.left if target < node.data else node.right return None

Insert and delete

Insert is search with a purpose: walk down as if searching; when you fall off the tree, attach the new node at that empty spot. It automatically lands in the only position that preserves the invariant. New nodes are always leaves.

Delete has three cases. Leaf: just remove it. One child: replace the node with that child. Two children: copy the inorder successor's value (the smallest value in the right subtree — step right once, then left to the bottom) into the node, then delete that successor node instead; the successor has at most a right child, so its deletion is one of the easy cases. All three operations are O(h).

def insert_bst(root, x): if root is None: return TreeNode(x) node = root while True: if x < node.data: if node.left is None: node.left = TreeNode(x) return root node = node.left elif x > node.data: if node.right is None: node.right = TreeNode(x) return root node = node.right else: return root # already present

Inorder traversal = sorted order

Do an inorder traversal (left, root, right) of a BST and the values come out in ascending order — a direct consequence of the invariant, provable by induction on the tree. This one fact powers a family of problems in this module: k-th smallest is the k-th element of the inorder walk; validating a BST can be done by checking the inorder sequence is strictly increasing; two-sum in a BST uses two inorder iterators (one ascending, one descending) as two pointers.

It also explains floor and ceil: while searching, keep the best candidate seen so far — the last node where you turned right is the floor candidate, symmetrically for ceil.

Complexity and common mistakes

Search, insert and delete are all O(h) time and O(1) iterative space (O(h) if recursive). Balanced: O(log n). Skewed: O(n) — a plain BST gives no balance guarantee.

Common mistakes: (1) validating with only local child comparisons instead of propagated min/max bounds; (2) in the two-children delete, copying the successor value but forgetting to then delete the successor node, duplicating it; (3) choosing the inorder predecessor vs successor inconsistently (either works if applied fully); (4) assuming insert keeps the tree balanced — it never rebalances, so input order determines shape; sorted input is the pathological case.

Key points

  • Invariant: left subtree values < node < right subtree values, for every node, over whole subtrees.
  • Search/insert/delete all cost O(h): O(log n) balanced, O(n) skewed — a plain BST does not self-balance.
  • Delete's hard case (two children) reduces to copying the inorder successor, then deleting that node.
  • Inorder traversal of a BST yields sorted order — the master key for k-th smallest, validation and two-sum problems.
  • Validate with propagated (min, max) bounds, not just parent-child comparisons.

Suggested questions

Search in BST ↗ The guided walk from this lesson, as a drill.
Insert a given node in BST ↗ Search until you fall off the tree, then attach the new leaf there.
Delete a node in BST ↗ All three cases, including the inorder-successor reduction for two children.
Check if a tree is a BST or not ↗ Apply the range-bounds validation — local child checks are not enough.
Minimum and Maximum in BST ↗ Leftmost and rightmost nodes — trivial once the invariant is internalised.

Source note: this lesson follows the structure of Striver's public A2Z DSA course (takeUforward). Each problem links to its original platform, and all problems and content belong to their respective owners — STUDY-BUDDY does not claim ownership of the sheet or its problems, and no permission beyond public linking is claimed.