Data structures and algorithms

Exercise solutions: Search trees

Here are suggested solutions to the exercises about search trees.

Core exercises

A1 and A2. Insert values into a tree

What you should notice is that for question A2, the binary search tree becomes extremely unbalanced, while the others do not because they are self-balancing!

A3. Implement the following functions on BSTs

A4. Implement set operations

union(s1, s2):
    for each x in s2:
        s1.add(x)

intersection(s1, s2):
    for x in s1:
        if not s2.contains(x):
            s1.remove(x)

difference(s1, s2):
    for x in s2:
        s1.remove(x)

Bonus part: We will only show the solution for difference.

Here are two ways to implement set difference, with different complexities:

Suppose that s1 has size M and s2 has size N (note different notation from the question because we use capital N and M). Then method 1 takes time proportional to N log(M), while method 2 takes time proportional to M log(max(M, N)). Therefore, the solution is:

A5. Sorting using a BST

A6. Multisets and multimaps

For a multiset: use a balanced BST map where the values are integers. Here are some possible operations:

For a multimap: use a balanced BST where the values are sets. Possible extra operations include:

Click here to see a more detailed implementation for multisets:
class Multiset:
    # e.g. using a map implemented using an AVL tree
    map = new AVLTree()

    add(x):
        if map.contains(x):
            count = map.get(x)
        else:
          count = 0
        map.put(x, count + 1)

    remove(x):
        if map.contains(x):
            count = map.get(x)
            if count == 1:
                map.remove(x)
            else:
                map.put(x, count - 1)

    count(x) -> int:
        if map.contains(x):
            return map.get(x)
        else:
            return 0

    contains(x) -> bool:
        return count(x) != 0

    # plus code for "union" from above

Bonus exercises

To be done.