1
Binary Search Tree (BST) ★★★★★
Data Structure
In a BST every left subtree value is smaller and every right subtree value is larger than the node. Inorder traversal gives sorted output. Search/insert/delete are O(log n) when balanced, O(n) when skewed.
A balanced BST with 7 nodes
Node* insert(Node *root, int x) {
if (!root) return new Node(x);
if (x < root->val) root->left = insert(root->left, x);
else root->right = insert(root->right, x);
return root;
}
bool search(Node *root, int x) {
while (root) {
if (x == root->val) return true;
root = (x < root->val) ? root->left : root->right;
}
return false;
}
Delete: leaf → remove; one child → replace with the child; two children → replace with the inorder successor (smallest in the right subtree), then delete that successor.