What is Binary search tree?
A binary tree in which, for every node, all values in the left subtree are smaller and all values in the right subtree are larger than the node. Search, insertion and deletion take time proportional to the tree's height, and an in-order traversal visits the values in ascending order.
Japanese name: 二分探索木
Binary search tree appears in 4 practice questions across 1 topic, including Data Structures and Algorithms.
Field: Data Structures and Algorithms
Unbalanced trees and self-balancing trees
A binary search tree with n nodes has a height of about log₂ n if it is balanced, but inserting values in sorted order, such as 1, 2, 3, …, produces a single chain extending to one side with height n−1. Searching it then takes O(n), the same as a linked list. AVL trees and red-black trees are self-balancing binary search trees that reshape themselves with operations called rotations on every insertion and deletion, keeping the height at O(log n); they are used for the ordered dictionaries and sets of many programming languages.
Traversal orders
Ways of visiting every node of a tree include pre-order, which visits each node first; in-order, which visits the left subtree, the node and then the right subtree; post-order, which visits the children first; and breadth-first (level-order), which visits the tree level by level. An in-order traversal of a binary search tree lists the values in ascending order, giving a sorted listing. A post-order traversal of an expression tree gives Reverse Polish notation.
FAQ
How does a binary search tree differ from a heap?
A binary search tree follows the rule “smaller on the left, larger on the right”, so it can search for any value and list values in order. A binary heap only follows the rule “a parent is larger (or smaller) than its children”, so it can quickly remove the maximum (or minimum) but is not suited to searching for arbitrary values.
When should a binary search tree or a B-tree be used?
In memory, self-balancing binary search trees are used; for storage read in blocks, such as disks and SSDs, B-trees (B+ trees), which keep the tree shallow by putting many keys in each node, are used.