Search, insert and delete
In a binary search tree every value in a node's left subtree is smaller and every value in its right subtree is larger. So search, insert, minimum, maximum and range counts each walk one path from the root: O(h), which is O(log n) when the tree is balanced. Deleting a node with two children replaces it with its inorder successor.
How to recognise it
- The data is a BST, or must be kept sorted while values are added and removed.
- Finding, inserting or deleting a value faster than scanning everything.
- Questions about values in a range, the smallest or the largest.
One path down
The rule that makes a BST, and how it compares with a heap, is on the Structures page.
| Task | Walk |
|---|---|
| search | go left when smaller, right when larger |
| insert | search until an empty spot; put the value there |
| min / max | far left / far right |
| count in [l, h] | skip a whole subtree when its values are all outside |
| build from preorder | each value goes into the range left by its ancestors |
Deleting
- No children: remove the node.
- One child: the child takes its place.
- Two children: copy in the inorder successor (the far left of the right subtree), then delete that value from the right subtree, which is case 1 or 2.
Balance
All of these are O(h). Sorted inserts make h = n. Rebuilding from the sorted inorder by always choosing the middle
as the root gives a tree of height about log n.
Common mistakes
- Comparing with only the parent when validating or inserting; the rule covers whole subtrees.
- Forgetting the two-children case when deleting.
Problems
- Search in a Binary Search Treeeasyguide ready
- Insert into a Binary Search Treemediumguide ready
- Delete Node in a BSTmediumguide ready
- Lowest Common Ancestor of a Binary Search Treemediumguide ready
- Construct Binary Search Tree from Preorder Traversalmediumguide ready
- Find min and max value in a BSTmediumguide ready
- Convert a normal BST into a Balanced BSTmediumguide ready
- Count BST ndoes that lie in a given rangemediumguide ready
- Given "n" appointments, find the conflicting appointmentsmediumguide ready