Browse curriculum

Binary Search Tree

A binary search tree is a hierarchical data structure in which each node has at most two children, with left child < parent < right child.

READY

In-order output

 

Insert a value, or press Random for a tree to search. Every operation walks down from the root.

 

Value

Order

Intuition

Imagine a family tree where every parent has at most two children. In a BST, we organize numbers so that everything to the left is smaller and everything to the right is larger. This makes finding a number very fast—like looking up a word in a dictionary!

Concept

In a binary search tree, every value in a node's left subtree is smaller than the node and every value in its right subtree is larger. That one ordering rule lets a search skip an entire subtree at every step: O(log n) when the tree is balanced, but O(n) when values arrive already sorted and the tree degenerates into a line.

How it Works

  • Root: The top node of the tree.
  • Left Subtree: Contains values smaller than the root.
  • Right Subtree: Contains values larger than the root.
  • Leaf: A node with no children.

Step-by-Step Breakdown

Insert(Value):
  1. Start at the Root.
  2. If Value < CurrentNode.Value, go Left.
  3. If Value > CurrentNode.Value, go Right.
  4. If you reach an empty spot (NULL), insert the new node there.

When to Use

  • Fast Lookup: Searching is O(log n) on average.
  • Sorted Data: In-order traversal gives sorted elements.
  • Dynamic Data: Efficient insertions and deletions compared to arrays.

When NOT to Use

  • Unbalanced Trees: In worst case (skewed tree), operations become O(n).
  • Constant Time Access: If you need O(1) access by index (use Array).

How to Identify

Look for problems involving searching, sorting, or maintaining a dynamic sorted set of elements. Keywords: "Binary Search", "Tree", "Hierarchy", "Sorted".

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description

Frequently Asked Questions

What is the BST invariant?

The property that for any node, all values in its left subtree are smaller than the node, and all values in its right subtree are larger.


What is the time complexity of BST operations?

In a balanced BST, operations are O(log n). However, in the worst case (a skewed tree), they can degrade to O(n).


How to handle duplicate values in a BST?

Commonly, duplicates are either ignored or stored by convention consistently in either the left or right subtree.