Binary Search Tree

Binary Search Tree — ExpertFunda

Binary Search Tree

By Babu • Updated

Binary Search Trees (BSTs) are a fundamental data structure in computer science. They allow efficient search, insertion and deletion operations. This guide explains the basics, key properties, common operations and some advanced balanced-tree ideas.

Basic Concepts

Node Structure

Each node stores a value and pointers to left and right children. By convention, left subtree contains smaller values, right subtree contains larger values.

Properties

  • Left subtree: values < current node.
  • Right subtree: values > current node.
  • Duplicates: usually avoided; if allowed, define a consistent policy (e.g. duplicates go to right).

Operations

Insertion

  1. Start at the root.
  2. Compare value, move left if smaller, right if larger.
  3. Insert at the null child position.

Deletion

Three cases: leaf node, node with one child, node with two children (replace with in-order successor or predecessor).

Search

  1. Start at root and compare.
  2. Follow left/right until found or null.

Traversals

  • In-order: left, root, right — yields sorted order.
  • Pre-order: root, left, right — useful to copy the tree.
  • Post-order: left, right, root — useful for deleting a tree.
  • Level-order: BFS using a queue.

Quick Code (Java — iterative search)

public TreeNode searchBST(TreeNode root, int val) {
  while (root != null) {
    if (val == root.val) return root;
    root = val < root.val ? root.left : root.right;
  }
  return null;
}

Watch our course on YouTube

Short playlist covering popular BST problems and approaches.

Advanced Topics

AVL Trees

AVL trees are strictly balanced binary search trees where the height difference between children is at most 1.

Red-Black Trees

Red-Black trees are balanced using color properties and provide good amortized performance for insertions and deletions.

FAQs

Efficient average-case search, insert and delete operations — O(log n) when balanced.

Inserting sorted data repeatedly can produce a degenerate tree (linked-list like), causing O(n) operations.

AVL trees maintain stricter height balance; Red-Black trees are less strict but cheaper for insert/delete in many workloads.

Usually duplicates are avoided. If required, choose a convention (e.g., insert duplicates to the right subtree) and document it.
© ExpertFunda — Built for learners and interview prep
Continue Reading →