right|upright=0.8|thumb|A binary search tree of size 9 and depth 3, with 8 at the root.
The leaves are not drawn.
In computer science, a binary search tree (BST), also called an ordered or sorted binary tree, is a rooted binary tree data structure whose internal nodes each store a key greater than all the keys in the node’s left subtree and less than those in its right subtree.
A binary tree is a type of data structure for storing data such as numbers in an organized way.
Binary search trees allow binary search for fast lookup, addition and removal of data items, and can be used to implement dynamic sets and lookup tables.
The order of nodes in a BST means that each comparison skips about half of the remaining tree, so the whole lookup takes time proportional to the binary logarithm of the number of items stored in the tree.
This is much better than the linear time required to find items by key in an (unsorted) array, but slower than the corresponding operations on hash tables.
Several variants of the binary search tree have been studied.
Definition
A binary search tree, also known as ordered binary search tree, is a variation of rooted binary tree in which the nodes are arranged in an order.
The nodes of the tree store a key (and optionally, an associated value), and each has two distinguished sub-trees, commonly denoted left and right.
The tree additionally satisfies the binary search property: the key in each node is greater than or equal to any key stored in the left sub-tree, and less than or equal to any key stored in the right sub-tree.
Thus, BST requires an order relation by which every node of the tree is comparable with every other node in the sense of total order.
Binary search trees are also efficacious in sorting algorithms and search algorithms.
However, the search complexity of a BST depends upon the order in which the nodes are inserted and deleted; since in worst case, successive operations in the binary search tree may lead to degeneracy and form a singly linked list (or "unbalanced tree") like structure, thus has the same worst-case complexity as a linked list.
Binary search trees are also a fundamental data structure used in construction of abstract data structures such as sets, multisets, and associative arrays.
Operations
Binary search trees support three main operations: lookup (checking whether a key is present), insertion, and deletion of an element.
The latter two possibly change the structural arrangement of the nodes in the tree, whereas the first one is a navigating and read-only operation.
Other read-only operations are traversal, verification, etc.
Searching
Searching in a binary search tree for a specific key can be programmed recursively or iteratively.
We begin by examining the root node.
If the tree is \text{nil}, the key we are searching for does not exist in the tree.
Otherwise, if the key equals that of the root, the search is successful and we return the node.
If the key is less than that of the root, we search the left subtree.
Similarly, if the key is greater than that of the root, we search the right subtree.
This process is repeated until the key is found or the remaining subtree is \text{nil}.
If the searched key is not found after a \text{nil} subtree is reached, then the key is not present in the tree.
Recursive search
The following pseudocode implements the BST search procedure through recursion.
Iterative search
The recursive version of the search can be "unrolled" into a while loop.
On most machines, the iterative version is found to be more efficient.
Since the search may proceed till some leaf node, the running time complexity of BST search is O(h) where h is the height of the tree.
However, the worst case for BST search is O(n) where n is the total number of nodes in the BST, because an unbalanced BST may degenerate to a linked list.
However, if the BST is height-balanced the height is O(\log n).
Maximum and minimum
Operations such as finding a node in a BST whose key is the maximum or minimum are critical in certain operations, such as determining the successor and predecessor of nodes.
Following is the pseudocode for the operations.
Successor and predecessor
For certain operations, given a node x, we need to find the successor or predecessor of x.
Assuming all the keys of the BST are distinct, the successor of a node x in BST is the node with the smallest key greater than x's key.
On the other hand, the predecessor of a node x in BST is the node with the largest key smaller than x's key.
Following is pseudocode for finding the successor and predecessor of a node x in BST.
Traversal
A BST can be traversed through three basic algorithms: inorder, preorder, and postorder tree walk.
Inorder tree walk:  Nodes from the left subtree get visited first, followed by the root node and right subtree.
Preorder tree walk: The root node gets visited first, followed by left and right subtrees.
Postorder tree walk: Nodes from the left subtree get visited first, followed by the right subtree, and finally the root.
Following is a recursive implementation of the tree walks.
Height
Height of the binary search tree is defined as the maximum of the heights of left subtree and right subtree incremented by a factor of 1.
Following is a recursive procedure for calculating the height of the BST given a root x:
Insertion
Operations such as insertion and deletion cause the BST representation to change dynamically.
The data structure must be modified in such a way that the properties of BST continue to hold.
New nodes are inserted as leaf nodes in the BST.
Following is an iterative implementation of the insertion operation.
The procedure maintains a "trailing pointer" y as a parent of x.
After initialization on line 2, the while loop along the lines 4-11 causes the pointers to be updated.
If y is nil, the BST is empty, thus z is inserted as the root node of the binary search tree T, if it isn't nil, we compare the keys on the lines 15-19 and insert the node accordingly.
Deletion
thumb|400px|Fig. 2: Binary search tree special cases deletion illustration.
Deletion of a node  \text{z} from a binary search tree \text{T} has three cases:
If \text{z} is a leaf node, we remove \text{z} by replacing its parent with \text{nil} as its child.
If \text{z} has only one child, we elevate that child—either left or right—to \text{z}'s position by modifying \text{z}'s parent by replacing it with \text{z}'s child, as shown in fig. 2 part (a) and (b).
If \text{z} has both a left and right child, we find \text{z}'s successor \text{y} and have it take \text{z}'s position in the tree.
\text{z}'s original right subtree becomes \text{y}'s new right subtree and \text{z}'s left subtree becomes \text{y}'s new left subtree respectively.
However, this case isn't trivial, since it depends on the position of \text{y} in the BST.
If \text{y} is \text{z}'s right child, we elevate \text{y} by leaving \text{y}'s right child alone, as shown in fig. 2 part (c).
If \text{y} isn't the right child, but lies within the right subtree and have a left child—either \text{nil} or a subtree—we first replace \text{y} by its own right child, and then replace \text{z} with \text{y}, as shown in fig. 2 part (d).
Following is a pseudocode for the deletion operation in a binary search tree.
The \text{Tree-Delete} procedure deals with the 3 special cases mentioned above.
Lines 2-3 deal with case 1; lines 4-5 deal with case 2 and lines 6-16 for case 3 respectively.
The helper function \text{Tree-Shift} is used within the deletion algorithm for the purpose of replacing the node \text{u} with \text{v} in the binary search tree \text{T}.
Examples of applications
Sort
A binary search tree can be used in sorting algorithm implementation.
The process involves inserting all the elements which are to be sorted and performing inorder traversal.
This method is similar to that of quicksort where each node corresponds to a partitioning item that subdivides its descendants into smaller keys and larger keys.
Priority queue operations
Binary search trees are used in implementing priority queues, using the element or node's key as priorities.
Adding new elements to the queue follows the regular BST \text{Tree-Insert} operation; but the removal operation depends on the type of priority queue:
If it's an ascending order priority queue, removal of an element with the lowest priority is done through leftward traversal of the BST i.e. \text{Tree-Minimum }.
On the other hand, if it's a descending order priority queue, removal of an element with the highest priority is done through rightward traversal of the BST i.e. \text{Tree-Maximum }.
Types
There are many types of binary search trees.
Self-balancing binary search trees modify the basic insertion and deletion operations of binary search trees, often using additional information on each node, in order to maintain logarithmic depth.
These include two early structures of this type, AVL trees, which maintain an invariant that subtree heights differ by at most one, and red-black trees, which instead color nodes red or black and maintain an invariant on the number of colored nodes on each root-to-leaf path.
These two types of tree are unified in the WAVL tree.
The T-tree is a height-balanced binary search tree optimized to reduce storage space overhead which are used for in-memory databases.
Weight-balanced trees achieve their logarithmic time bounds only in an amortized sense (summing over whole sequences of operations rather than analysing the time for each operation independently) but can be more flexible as part of recursive structures used in range searching.
When keys are inserted in a random order to a non-self-balancing binary tree, or drawn independently from a random distribution, without deletions, the resulting random binary search tree has both logarithmic expected depth, and logarithmic worst-case depth with high probability.
The treap (tree heap) is a self-balancing version of binary search trees that obtains the same behavior for worst-case operations, by assigning random priorities to each key and using the priorities to structure the tree as a Cartesian tree, with higher priorities at each node than at its children.
Certain types of self-balancing binary search trees have been designed to take advantage of non-uniform access patterns by handling frequently requested keys more quickly.
The performance of these online binary search trees can be analyzed by their competitive ratio, the maximum possible ratio of its running time on a sequence of access requests compared to the time of the best possible self-balancing binary search tree for the same access request.
Splay trees have been conjectured to have a constant competitive ratio, but this has not been proven.
The geometry of binary search trees gives a way of reformulating these problems geometrically, in terms of augmenting point sets to avoid axis-parallel rectangles with only two diagonal vertices present in the augmented set.
Another online binary search tree, the tango tree, is inspired by this geometric formulation, and has been proven to achieve an O(\log \log n) competitive ratio, while only using O(\log \log n) additional bits of memory per node.
A binary search tree may be "degenerate", by having only left children at every node, or by having only right children at every node.
When the resulting degenerate binary search tree contains n nodes it has height of n-1.
The performance or time complexity of a lookup operation is essentially identical with that of a linear search i.e. O(n), which is alike that of data structures like arrays or linked lists.
Performance comparisons
In regards to performance characteristics of binary search trees, a study shows that Treaps perform better on average case, while red–black tree was found to have the smallest number of performance variations.
Optimal binary search trees
Optimal binary search tree is a theoretical computer science problem which deals with constructing an "optimal" binary search trees that enables smallest possible search time for a given sequence of accesses.
The computational cost required to maintain an "optimal" search tree can be justified if search is more dominant activity in the tree than insertion or deletion.
Threaded binary trees
A threaded binary search tree is an accessorial version of a binary tree whose nil pointers—either left or right fields of a node—points to the inorder successor or inorder predecessor of the given nodes such that efficient utilization of the placeholders fields are performed.
Threading is classified into two categories:
One-way threading: The left or right pointer field of the nodes, holds a reference to the inorder predecessor or inorder successor, but not both.
Two-way threading: The left and right pointer fields hold the references to the inorder predecessor and inorder successor respectively.
See also
Binary search algorithm
Search tree
Join-based tree algorithms
Weight-balanced tree
Notes
References
Further reading
External links
Ben Pfaff: An Introduction to Binary Search Trees and Balanced Trees. (PDF; 1675 kB)
2004.
Binary Tree Visualizer (JavaScript animation of various BT-based data structures)
