Binary Search Tree
BST Topics
Binary Search Tree
Binary Search Trees (BSTs) are a fundamental data structure in computer science. They allow efficient search, insertion and deletion operations. This guide explains the basics, key properties, common operations and some advanced balanced-tree ideas.
Basic Concepts
Node Structure
Each node stores a value and pointers to left and right children. By convention, left subtree contains smaller values, right subtree contains larger values.
Properties
- Left subtree: values < current node.
- Right subtree: values > current node.
- Duplicates: usually avoided; if allowed, define a consistent policy (e.g. duplicates go to right).
Operations
Insertion
- Start at the root.
- Compare value, move left if smaller, right if larger.
- Insert at the null child position.
Deletion
Three cases: leaf node, node with one child, node with two children (replace with in-order successor or predecessor).
Search
- Start at root and compare.
- Follow left/right until found or null.
Traversals
- In-order: left, root, right — yields sorted order.
- Pre-order: root, left, right — useful to copy the tree.
- Post-order: left, right, root — useful for deleting a tree.
- Level-order: BFS using a queue.
Quick Code (Java — iterative search)
public TreeNode searchBST(TreeNode root, int val) {
while (root != null) {
if (val == root.val) return root;
root = val < root.val ? root.left : root.right;
}
return null;
}
Watch our course on YouTube
Short playlist covering popular BST problems and approaches.
Advanced Topics
AVL Trees
AVL trees are strictly balanced binary search trees where the height difference between children is at most 1.
Red-Black Trees
Red-Black trees are balanced using color properties and provide good amortized performance for insertions and deletions.