00:00

Binary Search Tree

Last updated:

A binary search tree (BST) is a binary tree that keeps its values in order. That one ordering rule turns a plain binary tree, where finding a value may mean checking every node, into a structure where each comparison discards a whole subtree.

What is Binary Search Tree?

A binary search tree is a binary tree (every node has at most a left and a right child) in which every node satisfies the BST property: all values in its left subtree are smaller than the node's value, and all values in its right subtree are larger.

To find a value, start at the root and compare: if the value is smaller, continue in the left subtree; if larger, in the right subtree. Each step goes one level down, so the cost is proportional to the tree's height. In a balanced BST that height is about log2 n; in the worst case (for example, after inserting values in sorted order) the tree degenerates into a chain and the height is n.

Binary search tree with root 50: left subtree 30, 20, 40, 25 and right subtree 70, 60, 80, 75

In the tree above, 50 is the root. Its left child 30 is the root of the left subtree, which holds only values smaller than 50 (20, 25, 30, 40), and its right child 70 is the root of the right subtree, which holds only values larger than 50 (60, 70, 75, 80).

Important points of Binary Search Tree (BST)

  • The left subtree of a node contains only keys smaller than the node's key.
  • The right subtree of a node contains only keys larger than the node's key.
  • Both the left and the right subtree are themselves binary search trees.
  • In the usual definition, keys are unique. If duplicates must be stored, a fixed rule is needed, such as "equal keys go to the right" or a count stored in each node.
  • An inorder traversal of a BST lists the keys in ascending order.

Operations On Binary Search Tree (BST)

The main operations, each of which follows a single path from the root:

  • Search: compare with the current node and go left or right until the key is found or a null link is reached (FAQ Q3).
  • Insert: search for the key; the null link where the search ends is where the new node goes (FAQ Q2).
  • Delete: a leaf is removed; a node with one child is replaced by that child; a node with two children takes the value of its inorder successor, which is then deleted (FAQ Q5).
  • Traversal: inorder gives sorted order; preorder, postorder and level order work as for any binary tree.
OperationAverage (balanced tree)Worst case (degenerate tree)
SearchO(log n)O(n)
InsertO(log n)O(n)
DeleteO(log n)O(n)
TraversalO(n)O(n)

Self-balancing BSTs such as AVL trees and red-black trees guarantee O(log n) for search, insert and delete in every case.