Kodewick
Start learning →
Binary search trees, set and map25 / 52

Binary search trees, set and map

Lesson 25 of 52 · Part 5 · Trees · about 22 minutes

A binary search tree keeps smaller values in the left subtree and bigger ones in the right, so search and insert walk one path down: O(log n) when balanced, O(n) when sorted input makes a chain; std::set and std::map stay O(log n) with a red-black tree.

A sorted array can be binary searched in O(log n), but inserting a value moves everything after it back, O(n). A linked list inserts by changing two pointers, but finding a value means walking from the front. Can both finding and inserting be fast? A binary search tree (BST) is the way: it makes binary search's "middle one" into a node of a tree.

Everything smaller on the left, bigger on the right

A binary search tree has one rule: every node's left subtree is all smaller than it, and its right subtree all bigger. So when you look for a value, one comparison with the current node tells you which way to go, and the whole other side never needs a look.

8
3
1
6
4
7
10
14
1TreeNode* find(TreeNode* t, int v) {2    while (t && t->val != v)3        t = v < t->val ? t->left : t->right;4    return t;5}

Looking for 7: each comparison throws away a whole subtree, and the root to 7 takes just 4 comparisons

Search and insert each walk one path down from the root, so the comparisons are at most the tree's height. When the tree is even, the height is about log₂ n, which is O(log n); and there is one more nice property: an inorder traversal of a binary search tree gives the values exactly in ascending order.

Choose one

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
Fill inTap one to fill a blank; tap a blank to take it back

Pick what goes in the blank so that find finds 7 but not 5, and the program prints 1 0.

1#include <iostream>2using namespace std;3 4struct TreeNode {5    int val;6    TreeNode *left, *right;7    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}8};9 10TreeNode* insert(TreeNode* t, int v) {11    if (t == nullptr) return new TreeNode(v);12    if (v < t->val) t->left = insert(t->left, v);13    else if (v > t->val) t->right = insert(t->right, v);14    return t;15}16 17TreeNode* find(TreeNode* t, int v) {18    while (t && t->val != v)19        t = v < t->val ?  : t->right;20    return t;21}22 23int main() {24    int a[] = {8, 3, 10, 1, 6, 14, 4, 7};25    TreeNode* t = nullptr;26    for (int x : a) t = insert(t, x);27    cout << (find(t, 7) != nullptr) << " " << (find(t, 5) != nullptr) << "\n";28    return 0;29}
Exercise 1

The smallest and the largest

Finish min_val and max_val: the smallest is furthest left, the largest furthest right.

It should print
20 80
exercise1.cpp
1#include <iostream>2using namespace std;3 4struct TreeNode {5    int val;6    TreeNode *left, *right;7    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}8};9 10TreeNode* insert(TreeNode* t, int v) {11    if (t == nullptr) return new TreeNode(v);12    if (v < t->val) t->left = insert(t->left, v);13    else if (v > t->val) t->right = insert(t->right, v);14    return t;15}16 17int min_val(TreeNode* t) {18    // keep going left until there is no left child19    return t->val;20}21 22int max_val(TreeNode* t) {23    // keep going right24    return t->val;25}26 27int main() {28    int a[] = {50, 30, 70, 20, 40, 60, 80, 35, 65};29    TreeNode* t = nullptr;30    for (int x : a) t = insert(t, x);31    cout << min_val(t) << " " << max_val(t) << endl;32    return 0;33}
Output
Press Run or Ctrl+Enter
Exercise 2

Is it a binary search tree?

Checking just "left child < this node < right child" isn't enough: every node in the left subtree must be smaller. Finish ok(t, lo, hi): every value in t must lie in (lo, hi).

It should print
1 0
exercise2.cpp
1#include <iostream>2#include <climits>3using namespace std;4 5struct TreeNode {6    int val;7    TreeNode *left, *right;8    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)9        : val(v), left(l), right(r) {}10};11 12bool ok(TreeNode* t, long long lo, long long hi) {13    // an empty tree is; this node outside (lo, hi) means it isn't; the left subtree's upper bound becomes this node, the right subtree's lower bound too14    return true;15}16 17int main() {18    TreeNode* good = new TreeNode(8, new TreeNode(3, new TreeNode(1), new TreeNode(6)), new TreeNode(10));19    // 9 is in 8's left subtree but bigger than 8: every node is fine next to its own children20    TreeNode* bad = new TreeNode(8, new TreeNode(3, new TreeNode(1), new TreeNode(9)), new TreeNode(10));21    cout << ok(good, LLONG_MIN, LLONG_MAX) << " " << ok(bad, LLONG_MIN, LLONG_MAX) << endl;22    return 0;23}
Output
Press Run or Ctrl+Enter

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 (nullptr) the new node goes there. The new node always hangs on as a leaf, and not one of the old nodes has to move.

8
3
1
6
4
7
10
14

Putting 5 in: smaller goes left, bigger goes right, and it goes into the empty place you reach
main.cpp
1#include <iostream>2using namespace std;3 4struct TreeNode {5    int val;6    TreeNode *left, *right;7    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}8};9 10TreeNode* insert(TreeNode* t, int v) {11    if (t == nullptr) return new TreeNode(v);    // reached an empty spot: it goes here12    if (v < t->val)13        t->left = insert(t->left, v);14    else if (v > t->val)15        t->right = insert(t->right, v);16    return t;                                    // an equal value isn't stored twice17}18 19TreeNode* find(TreeNode* t, int v) {20    while (t && t->val != v)21        t = v < t->val ? t->left : t->right;22    return t;23}24 25void in(TreeNode* t) {26    if (!t) return;27    in(t->left);28    cout << t->val << ' ';29    in(t->right);30}31 32void destroy(TreeNode* t) {33    if (!t) return;34    destroy(t->left);35    destroy(t->right);36    delete t;37}38 39int main() {40    int a[] = {8, 3, 10, 1, 6, 14, 4, 7};41    TreeNode* t = nullptr;42    for (int x : a)43        t = insert(t, x);44    in(t);45    cout << "\nfind 7: " << (find(t, 7) ? "yes" : "no")46         << ", find 5: " << (find(t, 5) ? "yes" : "no") << endl;47    destroy(t);48    return 0;49}
Output
1 3 4 6 7 8 10 14 
find 7: yes, find 5: no

insert returns the new root of the subtree, and the caller writes t->left = insert(t->left, v): only the call that reaches the empty spot really news a node, and every other level hands itself back unchanged. This is the most common pattern in recursive tree code.

Guess the outputA wrong guess is fine

Insert 5 2 8 1 4 9 in turn, then do a preorder traversal. What does it print?

1#include <iostream>2using namespace std;3 4struct TreeNode {5    int val;6    TreeNode *left, *right;7    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}8};9 10TreeNode* insert(TreeNode* t, int v) {11    if (t == nullptr) return new TreeNode(v);12    if (v < t->val) t->left = insert(t->left, v);13    else if (v > t->val) t->right = insert(t->right, v);14    return t;15}16 17void pre(TreeNode* t) {18    if (!t) return;19    cout << t->val << ' ';20    pre(t->left);21    pre(t->right);22}23 24int main() {25    int a[] = {5, 2, 8, 1, 4, 9};26    TreeNode* t = nullptr;27    for (int x : a) t = insert(t, x);28    pre(t);29    cout << endl;30    return 0;31}
Choose one

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 being deleted may have things hanging under it:

  1. A leaf: just delete it, and set the parent's pointer to nullptr.
  2. Only one child: the child moves up into its place.
  3. Two children: find the smallest node in its right subtree (the 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.
8
3
1
6
4
7
10
14

Deleting 3 (two children): the smallest in its right subtree is 4; copy 4 into 3's place, then delete the old 4

Cases 1 and 2 fold into one: take out the child that may be empty, delete this node, and hand the child back to the parent.

main.cpp
1#include <iostream>2using namespace std;3 4struct TreeNode {5    int val;6    TreeNode *left, *right;7    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}8};9 10TreeNode* insert(TreeNode* t, int v) {11    if (t == nullptr) return new TreeNode(v);12    if (v < t->val) t->left = insert(t->left, v);13    else if (v > t->val) t->right = insert(t->right, v);14    return t;15}16 17TreeNode* erase(TreeNode* t, int v) {18    if (t == nullptr) return nullptr;            // not found19    if (v < t->val) {20        t->left = erase(t->left, v);21    } else if (v > t->val) {22        t->right = erase(t->right, v);23    } else if (t->left == nullptr || t->right == nullptr) {24        TreeNode* child = t->left ? t->left : t->right;   // cases 1 and 225        delete t;26        return child;27    } else {                                     // case 3: find the successor28        TreeNode* s = t->right;29        while (s->left) s = s->left;30        t->val = s->val;31        t->right = erase(t->right, s->val);32    }33    return t;34}35 36void pre(TreeNode* t) {37    if (!t) return;38    cout << t->val << ' ';39    pre(t->left);40    pre(t->right);41}42 43int main() {44    int a[] = {8, 3, 10, 1, 6, 14, 4, 7};45    TreeNode* t = nullptr;46    for (int x : a) t = insert(t, x);47    t = erase(t, 3);                 // two children48    cout << "delete 3:  ";49    pre(t);50    t = erase(t, 10);                // one child51    cout << "\ndelete 10: ";52    pre(t);53    t = erase(t, 1);                 // a leaf54    cout << "\ndelete 1:  ";55    pre(t);56    cout << endl;57    return 0;58}
Output
delete 3:  8 4 1 6 7 10 14 
delete 10: 8 4 1 6 7 14 
delete 1:  8 4 6 7 14 
Choose one

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
Choose one

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
Put in orderDrag, or use the arrows

Deleting a node that has two children: put the four steps in order.

  1. Delete the old successor from the right subtree (it has no left child)
  2. In its right subtree, keep going left to the smallest: the successor
  3. Find the node to delete
  4. Copy the successor's value into the node being deleted

Inserting in order: a chain

A binary search tree's shape is decided by the order of the inserts. If the data is already sorted, every new value is bigger than the ones before, and they all hang to the right: the tree becomes a chain, and search falls back to O(n), as slow as a linked list.

1

Inserting 1 2 3 4 5 in order: each new value is bigger than all before it, so they all hang on the right
main.cpp
1#include <iostream>2#include <algorithm>3using namespace std;4 5struct TreeNode {6    int val;7    TreeNode *left, *right;8    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}9};10 11TreeNode* insert(TreeNode* t, int v) {12    if (t == nullptr) return new TreeNode(v);13    if (v < t->val) t->left = insert(t->left, v);14    else if (v > t->val) t->right = insert(t->right, v);15    return t;16}17 18int height(TreeNode* t) {19    if (!t) return 0;20    return max(height(t->left), height(t->right)) + 1;21}22 23int main() {24    TreeNode *a = nullptr, *b = nullptr;25    unsigned s = 7;26    for (int i = 0; i < 300; i++) {27        s = s * 1103515245 + 12345;28        a = insert(a, s % 100000);   // 300 shuffled values29        b = insert(b, i);            // 0, 1, 2, ..., 29930    }31    cout << "shuffled inserts: height " << height(a) << endl;32    cout << "sorted inserts: height " << height(b) << endl;33    return 0;34}
Output
shuffled inserts: height 17
sorted inserts: height 300

With 300 shuffled values the height is only 17 (log₂ 300 ≈ 8, and a randomly built tree is a bit over twice that); inserted in order, the height is 300: a chain. Balanced binary trees (AVL trees, red-black trees) exist for this problem: after an insert they rotate themselves so the height always stays O(log n). C++'s std::set and std::map are red-black trees inside; the last level of this lesson uses them.

OperationAverage (even tree)Worst (a chain)
SearchO(log n)O(n)
InsertO(log n)O(n)
DeleteO(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.

Choose allPick all that apply

Which of these orders, inserted into an empty tree, give a chain (height 5)? You can pick more than one.

Choose one

Insert 8 3 10 1 6 into an empty tree, in that order. What is the average search length (ASL) for a successful search?

With the STL

std::set<int> is a binary search tree of ints, and std::map<K, V> a binary search tree ordered by key, with a value in each node too. Inside they are red-black trees: after each insert or erase they rotate a few times, and the height never goes over 2 log₂ n, so whatever order the data comes in, it is O(log n). They match what you wrote yourself in this lesson one to one:

main.cpp
1#include <iostream>2#include <set>3#include <map>4#include <string>5using namespace std;6 7int main() {8    set<int> s;9    for (int x : {8, 3, 10, 1, 6, 14, 4, 7})10        s.insert(x);                   // your insert11    s.insert(6);                       // already there, not stored twice12    for (int x : s) cout << x << ' ';  // ascending: an inorder traversal13    cout << "\nsize " << s.size() << endl;14 15    cout << "is 7 there: " << (s.find(7) != s.end() ? "yes" : "no")16         << ", is 5 there: " << (s.count(5) ? "yes" : "no") << endl;17    s.erase(3);                        // your erase18    cout << "the first >= 5: " << *s.lower_bound(5) << endl;19    cout << "the first > 8: " << *s.upper_bound(8) << endl;20 21    map<string, int> cnt;              // key → value, also kept sorted by key22    for (string w : {"pear", "apple", "fig", "apple", "pear", "apple"})23        cnt[w]++;24    for (auto& kv : cnt)25        cout << kv.first << " " << kv.second << endl;26    return 0;27}
Output
1 3 4 6 7 8 10 14 
size 8
is 7 there: yes, is 5 there: no
the first >= 5: 6
the first > 8: 10
apple 3
fig 1
pear 2

lower_bound(5) walks the same path as a search: if the node is smaller than 5, go right; otherwise note it and go left; the last one noted is "the first not less than 5". 5 isn't in the tree, so you get 6. In a map, cnt[w] first inserts a node with value 0 if the key isn't there, then ++ runs.

Your own BST turns into a chain on sorted data; a set doesn't. Give the set a comparison that counts, and see how many comparisons each makes:

main.cpp
1#include <iostream>2#include <set>3using namespace std;4 5long cmps = 0;6 7struct CountLess {                     // the same as <, but counts each comparison8    bool operator()(int a, int b) const {9        cmps++;10        return a < b;11    }12};13 14struct TreeNode {15    int val;16    TreeNode *left, *right;17    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}18};19 20TreeNode* insert(TreeNode* t, int v) {21    if (t == nullptr) return new TreeNode(v);22    cmps++;23    if (v < t->val) t->left = insert(t->left, v);24    else if (v > t->val) t->right = insert(t->right, v);25    return t;26}27 28int main() {29    TreeNode* t = nullptr;30    for (int i = 0; i < 300; i++) t = insert(t, i);31    cout << "your BST: " << cmps << " comparisons" << endl;32 33    cmps = 0;34    set<int, CountLess> s;35    for (int i = 0; i < 300; i++) s.insert(i);36    cout << "std::set: " << cmps << " comparisons" << endl;37    return 0;38}
Output
your BST: 44850 comparisons
std::set: 3937 comparisons

Both get 0, 1, …, 299 in order. Your tree has to go to the bottom of the chain every time, 0 + 1 + … + 299 in all; the red-black tree stays balanced and goes down only a dozen or so levels each time.

Operationset / mapNotes
insert, find, count, eraseO(log n)One path down from the root
lower_bound, upper_boundO(log n)The first ≥ x / the first > x
Iterating from start to endO(n)Inorder: ascending
begin(), rbegin()O(1)The smallest, the largest

For repeated values, use multiset / multimap. When you only need "is it there" and don't care about order, unordered_set / unordered_map are faster, O(1) on average; use set / map when you need order or ranges ("which values are between 5 and 10").

In interviews: "Find the smallest value bigger than x", "keep a sorted group of values in a sliding window", "do these intervals overlap" are all set plus lower_bound problems. Use the member function s.lower_bound(x), not std::lower_bound(s.begin(), s.end(), x): the latter knows nothing of the tree, and on a set it is O(n).

Guess the outputA wrong guess is fine

The set holds 1 3 6 8. What does the program print?

1#include <iostream>2#include <set>3using namespace std;4 5int main() {6    set<int> s = {1, 3, 6, 8};7    cout << *s.lower_bound(4) << " " << *s.lower_bound(6) << " " << *s.upper_bound(6) << "\n";8    return 0;9}

Summary

Take-away

Binary search trees: smaller left, bigger right, one path down

  • Search and insert: compare with the node, smaller goes left, bigger right, O(height); inorder is ascending
  • Deleting a node with two children: the smallest in its right subtree (the successor) takes its place
  • Sorted inserts make a chain, O(n); balanced trees guarantee O(log n)
  • set / map are red-black trees: insert, find, erase and lower_bound are all O(log n)
1TreeNode* insert(TreeNode* t, int v) {2    if (!t) return new TreeNode(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}