Binary search trees
In a binary search tree (BST) every value in the left subtree is smaller than the node and every value in the right is bigger, so search and insert walk one path down in O(height), and an inorder traversal gives the values from smallest to largest.
A sorted array can be binary searched, O(log n), but inserting a value shifts everything after it, O(n). A linked list inserts by changing two pointers, but finding a value means walking from the front. Can we have both fast? A binary search tree (BST) does it: binary search's "middle one" made into the tree's nodes.
Smaller on the left, bigger on the right
A binary search tree has one rule: everything in a node's left subtree is smaller than it, everything in its right subtree bigger. So looking for a value, one comparison with the current node tells you which way to go, and the other side needn't be looked at at all.
Search and insert each walk one path down from the root, so they make at most as many comparisons as the tree is tall. In a well-balanced tree that's about log₂ n, O(log n). And a fine property: an inorder traversal of a binary search tree gives the values smallest to largest.
Looking for 5 in this binary search tree: how many nodes does it get compared with before you know 5 isn't there?
1 82 / \3 3 104 / \ \5 1 6 146 / \7 4 7
Pick what goes in the blank so that find finds 7 but not 5, and the program prints 1 0.
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 int val;6 struct Node *left, *right;7} Node;8 9Node *insert(Node *t, int v) {10 if (t == NULL) {11 t = malloc(sizeof(Node));12 t->val = v;13 t->left = t->right = NULL;14 } else if (v < t->val)15 t->left = insert(t->left, v);16 else if (v > t->val)17 t->right = insert(t->right, v);18 return t;19}20 21Node *find(Node *t, int v) {22 while (t && t->val != v)23 t = v < t->val ? : t->right;24 return t;25}26 27int main(void) {28 int a[] = {8, 3, 10, 1, 6, 14, 4, 7};29 Node *t = NULL;30 for (int i = 0; i < 8; i++)31 t = insert(t, a[i]);32 printf("%d %d\n", find(t, 7) != NULL, find(t, 5) != NULL);33 return 0;34}
t->left. t->right gets the direction backwards and doesn't find 7 either; t stays put, and the loop never ends.The smallest and the largest
✓Finish min_val and max_val: the smallest is at the far left, the largest at the far right.
20 80
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 int val;6 struct Node *left, *right;7} Node;8 9Node *insert(Node *t, int v) {10 if (t == NULL) {11 t = malloc(sizeof(Node));12 t->val = v;13 t->left = t->right = NULL;14 } else if (v < t->val)15 t->left = insert(t->left, v);16 else if (v > t->val)17 t->right = insert(t->right, v);18 return t;19}20 21int min_val(Node *t) {22 // keep going left until there's no left child23 return t->val;24}25 26int max_val(Node *t) {27 // keep going right28 return t->val;29}30 31int main(void) {32 int a[] = {50, 30, 70, 20, 40, 60, 80, 35, 65};33 Node *t = NULL;34 for (int i = 0; i < 9; i++)35 t = insert(t, a[i]);36 printf("%d %d\n", min_val(t), max_val(t));37 return 0;38}
Is it a binary search tree?
✓Checking "left child < node < right child" isn't enough: everything in the left subtree must be smaller. Finish ok(t, lo, hi): every value in t must be between lo and hi.
1 0
1#include <stdio.h>2#include <stdlib.h>3#include <limits.h>4 5typedef struct Node {6 int val;7 struct Node *left, *right;8} Node;9 10Node *node(int v, Node *l, Node *r) {11 Node *n = malloc(sizeof(Node));12 n->val = v; n->left = l; n->right = r;13 return n;14}15 16int ok(Node *t, long lo, long hi) {17 // an empty tree is; not between lo and hi, it isn't; the left subtree's upper limit becomes this node, the right's lower limit too18 return 1;19}20 21int main(void) {22 Node *good = node(8, node(3, node(1, NULL, NULL), node(6, NULL, NULL)), node(10, NULL, NULL));23 // 9 is in 8's left subtree but bigger than 8: every node is fine next to its children24 Node *bad = node(8, node(3, node(1, NULL, NULL), node(9, NULL, NULL)), node(10, NULL, NULL));25 printf("%d %d\n", ok(good, LONG_MIN, LONG_MAX), ok(bad, LONG_MIN, LONG_MAX));26 return 0;27}
Inserting: put it in the empty place you reach
Inserting walks the same path as searching: start at the root, go left when the value is smaller than the current node and right when it is bigger, and when you reach an empty place (NULL) the new node goes there. The new node always hangs on as a leaf, and not one of the old nodes has to move.
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 int val;6 struct Node *left, *right;7} Node;8 9Node *insert(Node *t, int v) {10 if (t == NULL) { // reached an empty place: it goes here11 t = malloc(sizeof(Node));12 t->val = v;13 t->left = t->right = NULL;14 } else if (v < t->val)15 t->left = insert(t->left, v);16 else if (v > t->val)17 t->right = insert(t->right, v);18 return t; // an equal value isn't put in twice19}20 21Node *find(Node *t, int v) {22 while (t && t->val != v)23 t = v < t->val ? t->left : t->right;24 return t;25}26 27void in(Node *t) {28 if (!t) return;29 in(t->left);30 printf("%d ", t->val);31 in(t->right);32}33 34int main(void) {35 int a[] = {8, 3, 10, 1, 6, 14, 4, 7};36 Node *t = NULL;37 for (int i = 0; i < 8; i++)38 t = insert(t, a[i]);39 in(t);40 printf("\nfind 7: %s, find 5: %s\n", find(t, 7) ? "yes" : "no", find(t, 5) ? "yes" : "no");41 return 0;42}
1 3 4 6 7 8 10 14 find 7: yes, find 5: no
insert returns the subtree's new root, and the caller writes t->left = insert(t->left, v): only the call that reaches the empty place really makes a node; every other level hands itself back as it was. It's the most common way to write tree recursion that changes the tree.
Insert 5 2 8 1 4 9 in that order, then a preorder traversal. What does it print?
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 int val;6 struct Node *left, *right;7} Node;8 9Node *insert(Node *t, int v) {10 if (t == NULL) {11 t = malloc(sizeof(Node));12 t->val = v;13 t->left = t->right = NULL;14 } else if (v < t->val)15 t->left = insert(t->left, v);16 else if (v > t->val)17 t->right = insert(t->right, v);18 return t;19}20 21void pre(Node *t) {22 if (!t) return;23 printf("%d ", t->val);24 pre(t->left);25 pre(t->right);26}27 28int main(void) {29 int a[] = {5, 2, 8, 1, 4, 9};30 Node *t = NULL;31 for (int i = 0; i < 6; i++)32 t = insert(t, a[i]);33 pre(t);34 printf("\n");35 return 0;36}
Insert 40 20 60 10 30 50 70 35 into an empty tree, in that order. Where does 35 end up?
Deleting: three cases
Deleting is harder than inserting, because the node may have things hanging under it:
- A leaf: just delete it, and set the parent's pointer to NULL.
- One child: the child moves up into its place.
- Two children: find the smallest in its right subtree (its successor, right after it in inorder), copy the successor's value over, then delete the successor from the right subtree. The successor never has a left child, so deleting it is case 1 or 2.
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 int val;6 struct Node *left, *right;7} Node;8 9Node *insert(Node *t, int v) {10 if (t == NULL) {11 t = malloc(sizeof(Node));12 t->val = v;13 t->left = t->right = NULL;14 } else if (v < t->val)15 t->left = insert(t->left, v);16 else if (v > t->val)17 t->right = insert(t->right, v);18 return t;19}20 21Node *del(Node *t, int v) {22 if (t == NULL) return NULL; // not found: nothing to do23 if (v < t->val)24 t->left = del(t->left, v);25 else if (v > t->val)26 t->right = del(t->right, v);27 else if (t->left && t->right) { // case 3: two children28 Node *s = t->right;29 while (s->left) s = s->left; // the successor: the leftmost node of the right subtree30 t->val = s->val;31 t->right = del(t->right, s->val);32 } else { // cases 1 and 2: at most one child, which moves up33 Node *c = t->left ? t->left : t->right;34 free(t);35 return c;36 }37 return t;38}39 40void pre(Node *t) {41 if (!t) return;42 printf("%d ", t->val);43 pre(t->left);44 pre(t->right);45}46 47int main(void) {48 int a[] = {8, 3, 10, 1, 6, 14, 4, 7};49 Node *t = NULL;50 for (int i = 0; i < 8; i++)51 t = insert(t, a[i]);52 t = del(t, 3); // two children53 t = del(t, 10); // one child54 t = del(t, 7); // a leaf55 pre(t);56 printf("\n");57 return 0;58}
8 4 1 6 14
In C, cases 1 and 2 can be written as one: with at most one child, that child (NULL for a leaf) moves up and the node is freed. Case 3 copies the successor's value first, then deletes the successor from the right subtree, which lands back in case 1 or 2.
Delete the root 50 from this tree (the successor takes its place). What is the root afterwards?
1 502 / \3 30 704 / \ / \5 20 40 60 806 / \7 35 65
Same tree, but this time delete 30 (the successor takes its place). What is in 30's place now?
1 502 / \3 30 704 / \ / \5 20 40 60 806 / \7 35 65
Deleting a node that has two children: put the four steps in order.
Delete the old successor from the right subtree (it has no left child)In its right subtree, keep going left to the smallest: the successorFind the node to deleteCopy the successor's value into the node being deleted
Inserting in order: a chain
A binary search tree's shape comes from the order things are inserted. If the data is already sorted, each new value is bigger than all before it and hangs on the right: the tree becomes a chain, and search drops back to O(n), as slow as a linked list.
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 int val;6 struct Node *left, *right;7} Node;8 9Node *insert(Node *t, int v) {10 if (t == NULL) {11 t = malloc(sizeof(Node));12 t->val = v;13 t->left = t->right = NULL;14 } else if (v < t->val)15 t->left = insert(t->left, v);16 else if (v > t->val)17 t->right = insert(t->right, v);18 return t;19}20 21int height(Node *t) {22 if (!t) return 0;23 int l = height(t->left), r = height(t->right);24 return (l > r ? l : r) + 1;25}26 27int main(void) {28 Node *a = NULL, *b = NULL;29 unsigned s = 7;30 for (int i = 0; i < 300; i++) {31 s = s * 1103515245 + 12345;32 a = insert(a, s % 100000); // 300 shuffled values33 b = insert(b, i); // 0, 1, 2, …, 29934 }35 printf("shuffled: height %d\n", height(a));36 printf("in order: height %d\n", height(b));37 return 0;38}
shuffled: height 17 in order: height 300
300 shuffled values make a tree only 17 tall (log₂ 300 ≈ 8, and a randomly built tree is a bit over twice that); inserted in order, it's 300 tall: a chain. Balanced trees (AVL trees, red-black trees) solve exactly this: after an insert they rotate themselves so the height stays O(log n). C++'s std::map and Java's TreeMap are red-black trees inside.
| Operation | Average (balanced) | Worst (a chain) |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Delete | O(log n) | O(n) |
In exams: "draw the binary search tree after inserting in this order", "the tree after deleting a node", "how many comparisons does finding a value take": walk it step by step, smaller left, bigger right. The average search length (ASL) for successful searches = the sum of each node's level, divided by the number of nodes.
Which of these orders, inserted into an empty tree, give a chain (height 5)? You can pick more than one.
1 5 2 4 3 is a chain that zigzags: 5 is right of 1, 2 left of 5, 4 right of 2, 3 left of 4, one node per level. In 3 1 4 2 5 the root 3 has children on both sides, and the height is just 3.Insert 8 3 10 1 6 into an empty tree, in that order. What is the average search length (ASL) for a successful search?
Summary
Binary search trees: smaller left, bigger right, one path down
- Search, insert: compare with the node, smaller left, bigger right, O(height)
- Inorder gives smallest to largest
- Deleting a node with two children: the smallest on its right (the successor) takes its place
- Sorted inserts make a chain, O(n); balanced trees keep O(log n)
1Node *insert(Node *t, int v) {2 if (!t) return new_node(v);3 if (v < t->val) t->left = insert(t->left, v);4 else if (v > t->val) t->right = insert(t->right, v);5 return t;6}