| Article Index |
|---|
| Binary Search Tree |
| Source code |
| Documentation |
| Tst case and compatibility |
| All Pages |
Binary search tree
In computer science, a binary search tree (BST) is a binary tree data structure which has the following properties:
- § Each node (item in the tree) has a distinct value.
- § Both the left and right subtrees must also be binary search trees.
- § The left subtree of a node contains only values less than the node's value.
- § The right subtree of a node contains only values greater than the node's value.
The major advantage of binary search trees over other data structures is that the related sorting algorithms and search algorithms such as in-order traversal can be very efficient.
Binary search trees can choose to allow or disallow duplicate values, depending on the implementation.
Binary search trees are a fundamental data structure used to construct more abstract data structures such as sets, multisets, and associative arrays.
OPERATIONS
Operations on a binary tree require comparisons between nodes.
Searching
Searching a binary tree for a specific value can be a recursive or iterative process.
Insertion
Insertion begins as a search would begin; if the root is not equal to the value, we search the left or right subtrees as before. Eventually, we will reach an external node and add the value as its right or left child, depending on the node's value. In other words, we examine the root and recursively insert the new node to the left subtree if the new value is less than the root, or the right subtree if the new value is greater than or equal to the root.
Deletion
There are several cases to be considered:
- § Deleting a leaf: Deleting a node with no children is easy, as we can simply remove it from the tree.
- § Deleting a node with one child: Delete it and replace it with its child.
- § Deleting a node with two children: Suppose the node to be deleted is called N. We replace the value of N with either its in-order successor (the left-most child of the right subtree) or the in-order predecessor (the right-most child of the left subtree).
![]()
Once we find either the in-order successor or predecessor, swap it with N, and then delete it. Since both the successor and the predecessor must have fewer than two children, either one can be deleted using the previous two cases. A good implementation avoids consistently using one of these nodes, however, because this can unbalance the tree.
Traversal
Once the binary search tree has been created, its Elements can be retrieved in-order by recursively traversing the left subtree of the root node, accessing the node itself, then recursively traversing the right subtree of the node, continuing this pattern with each node in the tree as it's recursively accessed. The tree may also be traversed in pre-order or post-order traversals.
| < Prev | Next > |
|---|




