Binary Search Trees - aloalgo.com

Binary Search Trees

A Binary Search Tree (BST) is a binary tree with an ordering property: for every node, all values in its left subtree are less than the node's value, and all values in its right subtree are greater. This property enables efficient searching, insertion, and deletion.

The BST Property

The defining characteristic of a BST is:
  • Left subtree: All values are less than the node
  • Right subtree: All values are greater than the node
  • Both subtrees must also be valid BSTs

BST Node Structure

Core Operations

OperationAverageWorstDescription
SearchO(log n)O(n)Compare and go left or right until found
InsertO(log n)O(n)Search for position, then add as leaf
DeleteO(log n)O(n)Find node, handle 0/1/2 children cases
Min/MaxO(log n)O(n)Go all the way left (min) or right (max)
Note: Worst case O(n) occurs when the tree is skewed (like a linked list). Balanced BSTs like AVL or Red-Black trees guarantee O(log n).

Search

Start at the root. If target equals current value, found. If target is smaller, go left. If larger, go right. Repeat until found or reach null.

Insert

Search for where the value should be, then insert as a new leaf node.

Delete

Deletion has three cases:
  1. Leaf node: Simply remove it
  2. One child: Replace node with its child
  3. Two children: Replace with inorder successor (or predecessor), then delete that node

Inorder Traversal = Sorted Order

A key property of BSTs: inorder traversal visits nodes in sorted order. This is extremely useful for validation and many BST problems.

Validate BST

To check if a tree is a valid BST, ensure each node's value falls within valid bounds (updated as you traverse).

BST vs Hash Table

FeatureBSTHash Table
SearchO(log n)O(1) average
Ordered iterationYes (inorder)No
Min/MaxO(log n)O(n)
Range queriesEfficientInefficient
Floor/CeilingO(log n)O(n)
Use BST when you need: Sorted data, range queries, finding predecessors/successors, or min/max operations.

Common Interview Tips

  1. Inorder traversal: Many BST problems can be solved by leveraging the sorted inorder property.
  2. Bounds checking: For validation problems, pass min/max bounds down the recursion.
  3. Predecessor/Successor: The inorder predecessor is the rightmost node in the left subtree; successor is leftmost in right subtree.
  4. LCA in BST: Unlike general trees, you can use the BST property to find LCA in O(h) without visiting all nodes.
  5. Watch for duplicates: Clarify how duplicates should be handled (often placed in right subtree).
Was this helpful?
© 2026 aloalgo.com. All rights reserved.