Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 7 – Binary Search Trees

Part 1 – A binary search tree

class Node {
    int data;
    Node left, right;
    Node(int data) {
        this.data = data;
        left = right = null;
    }
}
public class Bst {
    Node root = null;
    // the methods below
}

Task 1 – Iterative insertion

Go down from the root as in a search, remembering the last node visited (prev). When you fall off the tree, attach the new node to prev, on the correct side. Ignore duplicates.

public void insert(int x) {
    // ToDo
}
Solution
public void insert(int x) {
    Node n = new Node(x);
    if (root == null) {
        root = n;
        return;
    }
    Node p = root, prev = null;
    while (p != null) {                 // go down as in a search
        if (x == p.data)
            return;                     // already there: no duplicates
        prev = p;
        p = (x < p.data) ? p.left : p.right;
    }
    if (x < prev.data) prev.left = n;   // prev is the last node visited
    else               prev.right = n;
}

Task 2 – Recursive insertion

private Node insertR(Node start, int x) {
    // ToDo
}
public void insertRec(int x) {
    root = insertR(root, x);
}
Solution
private Node insertR(Node start, int x) {
    if (start == null)
        return new Node(x);             // the new leaf
    if (x < start.data)
        start.left = insertR(start.left, x);
    else if (x > start.data)
        start.right = insertR(start.right, x);
    return start;
}
public void insertRec(int x) {
    root = insertR(root, x);
}

Task 3 – Search and minimum

contains follows one path from the root; the minimum is the leftmost node.

public boolean contains(int x) { /* ToDo */ }
private int minimum(Node start) { /* ToDo */ }
public int min() { return minimum(root); }
Solution
public boolean contains(int x) {
    Node p = root;
    while (p != null) {
        if (x == p.data) return true;
        p = (x < p.data) ? p.left : p.right;
    }
    return false;
}

private int minimum(Node start) {       // start must not be null
    while (start.left != null)
        start = start.left;
    return start.data;
}
public int min() {
    return minimum(root);
}

Task 4 – Deletion

Three cases: a leaf, a node with one child (return the other child), a node with two children (copy the minimum of the right subtree into the node, then delete that minimum from the right subtree).

private Node delete_Recursive(Node start, int key) {
    // ToDo
}
public void delete(int key) {
    root = delete_Recursive(root, key);
}
Solution
private Node delete_Recursive(Node start, int key) {
    if (start == null)
        return null;                    // key not found
    if (key < start.data)
        start.left = delete_Recursive(start.left, key);
    else if (key > start.data)
        start.right = delete_Recursive(start.right, key);
    else {
        if (start.left == null)  return start.right;   // leaf or one child
        if (start.right == null) return start.left;
        start.data = minimum(start.right);             // two children
        start.right = delete_Recursive(start.right, start.data);
    }
    return start;
}
public void delete(int key) {
    root = delete_Recursive(root, key);
}

Task 5 – Traversals and height

Write inorder() (it prints the keys sorted), preorder() (it shows the shape), and height().

Solution
private void inorder(Node p) {
    if (p == null) return;
    inorder(p.left);
    System.out.print(p.data + " ");
    inorder(p.right);
}
public void inorder() { inorder(root); System.out.println(); }

private void preorder(Node p) {
    if (p == null) return;
    System.out.print(p.data + " ");
    preorder(p.left);
    preorder(p.right);
}
public void preorder() { preorder(root); System.out.println(); }

private int height(Node p) {
    return p == null ? -1 : 1 + Math.max(height(p.left), height(p.right));
}
public int height() { return height(root); }

Test your BST

The keys are those of the final exam.

Bst t = new Bst();
int[] keys = {7, 14, 13, 20, 21, 15, 9, 11, 25};   // final exam
for (int k : keys)
    t.insertRec(k);
System.out.print("inorder:  "); t.inorder();
System.out.print("preorder: "); t.preorder();
System.out.println("height " + t.height() + ", min " + t.min()
                   + ", contains 15? " + t.contains(15)
                   + ", contains 16? " + t.contains(16));
t.delete(14);             // two children: replaced by 15
System.out.print("after delete(14): "); t.preorder();
t.delete(21);             // one child: 25 moves up
System.out.print("after delete(21): "); t.preorder();
t.delete(11);             // a leaf
System.out.print("after delete(11): "); t.preorder();
t.delete(7);              // the root, with only a right child
System.out.print("after delete(7):  "); t.preorder();

Bst u = new Bst();        // the iterative insertion builds the same tree
for (int k : keys)
    u.insert(k);
System.out.print("iterative insert, preorder: "); u.preorder();

Expected output:

inorder:  7 9 11 13 14 15 20 21 25 
preorder: 7 14 13 9 11 20 15 21 25 
height 4, min 7, contains 15? true, contains 16? false
after delete(14): 7 15 13 9 11 20 21 25 
after delete(21): 7 15 13 9 11 20 25 
after delete(11): 7 15 13 9 20 25 
after delete(7):  15 13 9 20 25 
iterative insert, preorder: 7 14 13 9 11 20 15 21 25 

Part 2 – Use the JDK

Challenge 1 – A leaderboard

Store the scores 72 Omar, 95 Sara, 88 Ali, 64 Huda, 91 Khalid in a TreeMap<Integer, String>. Print the best and the worst player, the top 3, the scores between 70 and 90, and the score just below 90.

Solution
static void leaderboard() {
    TreeMap<Integer, String> scores = new TreeMap<>();   // score -> player
    scores.put(72, "Omar");
    scores.put(95, "Sara");
    scores.put(88, "Ali");
    scores.put(64, "Huda");
    scores.put(91, "Khalid");

    System.out.println("best: " + scores.lastEntry());
    System.out.println("worst: " + scores.firstEntry());
    System.out.println("top 3: " + scores.descendingMap().headMap(88, true));
    System.out.println("between 70 and 90: " + scores.subMap(70, true, 90, true));
    System.out.println("just below 90: " + scores.lowerEntry(90));
}

Expected output:

best: 95=Sara
worst: 64=Huda
top 3: {95=Sara, 91=Khalid, 88=Ali}
between 70 and 90: {72=Omar, 88=Ali}
just below 90: 88=Ali

Challenge 2 – Booking a room without overlaps

Bookings are intervals [start, end) stored in a TreeMap<Integer, Integer> (start → end). A new booking is accepted only if it overlaps neither the booking that starts just before it (floorEntry) nor the one that starts just after (ceilingEntry). Each request costs O(log⁡n)O(\log n) instead of checking every booking.

Solution
static TreeMap<Integer, Integer> booked = new TreeMap<>();   // start -> end

// book [start, end) if it does not overlap an existing booking
static boolean book(int start, int end) {
    Map.Entry<Integer, Integer> before = booked.floorEntry(start);   // starts <= start
    Map.Entry<Integer, Integer> after = booked.ceilingEntry(start);  // starts >= start
    if (before != null && before.getValue() > start) return false;
    if (after != null && after.getKey() < end) return false;
    booked.put(start, end);
    return true;
}
System.out.println(book(10, 12) + " " + book(14, 16) + " " + book(11, 13)
                   + " " + book(12, 14) + " " + book(9, 10));
System.out.println(booked);

Expected output:

true true false true true
{9=10, 10=12, 12=14, 14=16}

Challenge 3 – A sorted dictionary of words

Put the words of "the quick brown fox jumps over the lazy dog the end" in a TreeSet. Print them, the first and the last word, the words before "m", and the word that comes right after "fox".

Solution
String text = "the quick brown fox jumps over the lazy dog the end";
TreeSet<String> words = new TreeSet<>(Arrays.asList(text.split(" ")));
System.out.println(words);                          // sorted, no duplicates
System.out.println("first: " + words.first() + ", last: " + words.last());
System.out.println("before \"m\": " + words.headSet("m"));
System.out.println("after \"fox\": " + words.higher("fox"));

Expected output:

[brown, dog, end, fox, jumps, lazy, over, quick, the]
first: brown, last: the
before "m": [brown, dog, end, fox, jumps, lazy]
after "fox": jumps