<< Chapter < Page | Chapter >> Page > |
(From Wikipedia, the free encyclopedia)
A binary search tree of size 9 and depth 3, with root 8 and leaves 1, 4, 7 and 13.
In computer science , a binary search tree (BST) is a binary tree data structure which has the following properties:
The major advantage of binary search trees is that the related sorting algorithms and search algorithms such as in-order traversal can be very efficient.
Binary search trees are a fundamental data structure used to construct more abstract data structures such as sets , multisets , and associative arrays .
If a BST allows duplicate values, then it represents a multiset. This kind of tree uses non-strict inequalities. Everything in the left subtree of a node is strictly less than the value of the node, but everything in the right subtree is either greater than or equal to the value of the node.
If a BST doesn't allow duplicate values, then the tree represents a set with unique values, like the mathematical set. Trees without duplicate values use strict inequalities, meaning that the left subtree of a node only contains nodes with values that are less than the value of the node, and the right subtree only contains values that are greater.
The choice of storing equal values in the right subtree only is arbitrary; the left would work just as well. One can also permit non-strict equality in both sides. This allows a tree containing many duplicate values to be balanced better, but it makes searching more complex.
All operations on a binary tree make several calls to a comparator , which is a subroutine that computes the total order on any two values. In generic implementations of binary search trees, a program often provides a callback to a comparator when it creates a tree, either explicitly or, in languages that support type polymorphism , by having values be of a comparable type.
(From Wikipedia, the free encyclopedia)
Searching a binary tree for a specific value is a process that can be performed recursively because of the order in which values are stored. We begin by examining the root. If the value we are searching for equals the root, the value exists in the tree. If it is less than the root, then it must be in the left subtree, so we recursively search the left subtree in the same manner. Similarly, if it is greater than the root, then it must be in the right subtree, so we recursively search the right subtree. If we reach a leaf and have not found the value, then the item is not where it would be if it were present, so it does not lie in the tree at all. A comparison may be made with binary search , which operates in nearly the same way but using random access on an array instead of following links.
Here is the search algorithm in the Python programming language :
Notification Switch
Would you like to follow the 'Data structures and algorithms' conversation and receive update notifications?