Binary search tree
Бинарное дерево поиска
This data structure stores keys in a tree where each node has at most two children. Smaller keys go in its left subtree and larger keys go in its right, so a lookup only needs to follow one path.
Also known as: BST
The rule that makes search work
A binary search tree (BST) organizes comparable keys, such as numbers or strings. Every key anywhere in a node’s left subtree must be smaller than that node’s key, and every key in its right subtree must be larger. That ordering rule is what distinguishes a BST from an arbitrary binary tree. It also means a lookup can rule out an entire subtree with one comparison.
The strict ordering above assumes unique keys. If you need to represent duplicates, one option is to keep a count at each node instead of adding another node with the same key.
Look up, insert, and delete
To find a key, start at the root. Return the current node if the keys match. Otherwise, follow the left child if the target is smaller or the right child if it is larger. Reaching a missing child means the key is absent. Insertion follows the same comparisons and attaches a new node at that missing link; inserting into an empty tree sets its root.
Deletion depends on how many children the node has. Remove a leaf outright, or replace a node with one child by that child. For a node with two children, find its in-order successor: the smallest key in the right subtree. Move that key and its associated value into the node being deleted, then remove the successor from its original position. The successor has no left child, so the second removal is one of the simpler cases.
Walking through an example
8
/ \
4 13
\ /
6 11
To find 11, go right from 8, then left from 13. To list all the keys in order, visit the left subtree, then the node, then the right subtree. This in-order traversal yields 4, 6, 8, 11, 13 and takes O(n) time because it visits every node.
Why height matters in practice
Lookup, insertion, and deletion take O(h) time, where h is the tree’s height. A balanced tree keeps that height at O(log n) for n nodes. A plain BST does not guarantee balance: inserting already sorted keys can create a chain, making operations take O(n) in the worst case.
Self-balancing BSTs such as AVL and red-black trees avoid that worst-case shape. They are useful for ordered sets and maps: Java’s TreeMap, for example, uses a red-black tree. A hash table is often a better fit if you only need exact lookups, but an ordered tree also lets you find the next larger key or iterate over a range without scanning every entry.
What interviewers look for
A common task is to validate a BST. The trap is checking each node only against its children: a 9 may be on the correct side of its parent and still be invalid anywhere in the left subtree of 8. Carry a lower and upper bound down the tree so each node is checked against the constraints inherited from its ancestors.