Binary Search Trees

CSCI 1913 – Introduction to Algorithms, Data Structures, and Program Development
Adriana Picoral

Typically, some type of ordering will be imposed on the elements in a binary tree.

Binary Search Trees

  • Arrays provide fast random access but inserting/deleting is slow
  • Linked lists make insertion easy but searching is slow

What if we want something that’s reasonably fast at both searching and inserting?

We will start by taking a look at binary search trees and will look at different kinds of balanced trees and set/dictionary implementations later

Binary Search Trees

A Binary Search Tree (BST) is a linked structure where:

  • each node has at most two children
  • everything in the left subtree is smaller than that node
  • everything in the right subtree is larger than that node

Repeated values can be handled differently, we will be implementing a strict BST (disallow duplicates).

Binary Search Trees

Each node has at most two children

BST 10 10 5 5 10--5 15 15 10--15 3 3 5--3 8 8 5--8 12 12 15--12 20 20 15--20 1 1 3--1 4 4 3--4 6 6 8--6 9 9 8--9 11 11 12--11 null1 12--null1 16 16 20--16 25 25 20--25 null2 25--null2 28 28 25--28

Binary Search Trees

Everything in a left subtree is smaller than its parent node

BST 5 5 3 3 5--3 8 8 5--8 1 1 3--1 4 4 3--4 10 10 10--5 15 15 10--15 12 12 15--12 20 20 15--20 6 6 8--6 9 9 8--9 11 11 12--11 null1 12--null1 16 16 20--16 25 25 20--25 null2 25--null2 28 28 25--28

Binary Search Trees

Everything in a right subtree is larger than its parent node

BST 10 10 5 5 10--5 15 15 10--15 3 3 5--3 8 8 5--8 12 12 15--12 20 20 15--20 1 1 3--1 4 4 3--4 6 6 8--6 9 9 8--9 11 11 12--11 null1 12--null1 16 16 20--16 25 25 20--25 null2 25--null2 28 28 25--28

Binary Search Trees

We will look at 5 functions:

  • add
  • remove
  • findMin
  • findMax
  • search (specific to BST)

Add

Data in Node that we want to add: 7

What do we have to do to add Node 7 to the right spot?

BST 10 10 5 5 10--5 15 15 10--15 3 3 5--3 8 8 5--8 12 12 15--12 20 20 15--20 1 1 3--1 4 4 3--4 6 6 8--6 9 9 8--9 11 11 12--11 null1 12--null1 16 16 20--16 25 25 20--25 null2 25--null2 28 28 25--28

Add

Compare value to be added to root

BST 7 7 10 10 5 5 10--5 15 15 10--15 3 3 5--3 8 8 5--8 12 12 15--12 20 20 15--20 1 1 3--1 4 4 3--4 6 6 8--6 9 9 8--9 11 11 12--11 null1 12--null1 16 16 20--16 25 25 20--25 null2 25--null2 28 28 25--28

Add

7 is less than 10, so our next comparison is with the root of the left subtree

BST 7 7 10 10 5 5 10--5 15 15 10--15 3 3 5--3 8 8 5--8 12 12 15--12 20 20 15--20 1 1 3--1 4 4 3--4 6 6 8--6 9 9 8--9 11 11 12--11 null1 12--null1 16 16 20--16 25 25 20--25 null2 25--null2 28 28 25--28

Add

7 is greater than 5, so our next comparison is with the root of the right subtree

BST 7 7 10 10 5 5 10--5 15 15 10--15 3 3 5--3 8 8 5--8 12 12 15--12 20 20 15--20 1 1 3--1 4 4 3--4 6 6 8--6 9 9 8--9 11 11 12--11 null1 12--null1 16 16 20--16 25 25 20--25 null2 25--null2 28 28 25--28

Add

7 is less than 8, so our next comparison is with the root of the left subtree

BST 7 7 10 10 5 5 10--5 15 15 10--15 3 3 5--3 8 8 5--8 12 12 15--12 20 20 15--20 1 1 3--1 4 4 3--4 6 6 8--6 9 9 8--9 11 11 12--11 null1 12--null1 16 16 20--16 25 25 20--25 null2 25--null2 28 28 25--28

Add

7 is greater than 6, so our next comparison is with the root of the right subtree – the right node is null, so that’s where our node to be added goes.

BST 10 10 5 5 10--5 15 15 10--15 3 3 5--3 8 8 5--8 12 12 15--12 20 20 15--20 1 1 3--1 4 4 3--4 6 6 8--6 9 9 8--9 null 6--null 7 7 6--7 11 11 12--11 null1 12--null1 16 16 20--16 25 25 20--25 null2 25--null2 28 28 25--28

Binary Search Trees

BSTs are only efficient when they’re balanced.

In the worst case you get O(n) operations – how?

You will learn about self-balancing trees like AVL trees and Red-Black trees (later)

Binary Search Trees

In the worst case you get O(n) operations – how? Add 90 to tree:

BST 100 100 leftNull 100--leftNull rightNull 100--rightNull

Binary Search Trees

In the worst case you get O(n) operations – how? Add 80 to tree:

BST 100 100 90 90 100--90 null 100--null

Binary Search Trees

In the worst case you get O(n) operations – how? Add 79 to tree:

BST 100 100 90 90 100--90 null 100--null 80 80 90--80 null2 90--null2

Binary Search Trees

In the worst case you get O(n) operations – how? Add 65 to tree:

BST 100 100 90 90 100--90 null 100--null 80 80 90--80 null2 90--null2 79 79 80--79 null3 80--null3

Binary Search Trees

In the worst case you get O(n) operations – how? Add 42 to tree:

BST 100 100 90 90 100--90 null 100--null 80 80 90--80 null2 90--null2 79 79 80--79 null3 80--null3 65 65 79--65 null4 79--null4

Binary Search Trees

In the worst case you get O(n) operations – how? Add 26 to tree:

BST 100 100 90 90 100--90 null 100--null 80 80 90--80 null2 90--null2 79 79 80--79 null3 80--null3 65 65 79--65 null4 79--null4 42 42 65--42 null5 65--null5

Binary Search Trees

In the worst case you get O(n) operations – how?

BST 100 100 90 90 100--90 null 100--null 80 80 90--80 null2 90--null2 79 79 80--79 null3 80--null3 65 65 79--65 null4 79--null4 42 42 65--42 null5 65--null5 26 26 42--26 null6 42--null6

The tree is now a linked list: search takes O(n)

Self-balancing Binary Search Trees (BBSTs)

The solution to this problem is Self-balancing Binary Search Trees (BBSTs).

  • AVL Trees: keeps the height difference (balance factor) between the left and right subtrees of every node at ≤ 1
  • Red-Black Trees: gives a color (red or black) to each node along with structural rules (for example, the root is black, red nodes cannot have red children, and all paths from a node to its leaves have the same number of black nodes).

We will not be implementing a self-balancing binary search tree in class.

Java implementation

Tree – interface

The data type T must implement Comparable so we can decide whether to go left or right (we use compareTo from the data object – this is a bounded generic type)

public interface Tree<T extends Comparable<T>> {
   Node<T> getRoot();
   void addNode(Node<T> node);
   Node<T> findMin();
   Node<T> findMax();
   void remove(T value);
}

compareTo convention used in all our methods: value.compareTo(current.getData())

  • negative – value is smaller, go left (for BST)
  • positive – value is larger, go right (for BST)
  • zero – found it (or a duplicate)

BST Node implementation

We are implementing our BST as a linked binary tree (that’s how it’s usually done). Implement a Node.java file for a Binary Search Tree.

  • What are the instance variables?
  • The constructor should set the data in the node
  • Getter and setters for all instance variables.

BST Node implementation

Here’s our generic Node class:

public class Node<T extends Comparable<T>> {
    private T data;
    private Node<T> left;
    private Node<T> right;

    // constructor with data as argument
    public Node(T data) {
        this.data = data;
        left = null;
        right = null;
    }

    // getters
    public T getData() {
        return data;
    }

    public Node<T> getLeft() {
        return left;
    }

    public Node<T> getRight() {
        return right;
    }

    // setters
    public void setData(T data) {
        this.data = data;
    }

    public void setLeft(Node<T> node) {
        left = node;
    }

    public void setRight(Node<T> node) {
        right = node;
    }

}

BST implementation (basics)

  • We need a reference to the root as an instance variable
  • Getter for root (getRoot())

BST implementation (basics)

public class BST<T extends Comparable<T>> implements Tree<T>{
    private Node<T> root;

    public BST() {
        root = null;
    }
  
    public Node<T> getRoot() {
        return root;
    }

    public void addNode(Node<T> node) {}
    public Node<T> findMin() {return null;}
    public Node<T> findMax() {return null;}
    public void remove(T value) {};
    
}

Add – strategy

  • Check if tree is empty (is root null?), if so the node to add is the root
  • If tree is not empty, find the spot to add (I’ll do that recursively)

public addNode

public void addNode(Node<T> node) {
  if (root == null) {
    root = node;
  } else {
    addNode(root, node);
  }
}

private addNode

This recursive method should be private.

private void addNode(Node<T> current, Node<T> nodeToAdd)

Strategy:

  • Decide if you need to go left or right (use compareTo)
  • Check if left/right (whatever path you need to take) child is null, if so, set current node child to nodeToAdd
  • If left/right child is not null, call addNode recursively with left/right child as current node

Test it

Tree<Character> tree = new BST<>();

tree.addNode(new Node<>('M'));
System.out.println(tree.getRoot().getData());

tree.addNode(new Node<>('O'));
System.out.println(tree.getRoot().getLeft());
System.out.println(tree.getRoot().getRight().getData());

Submit your Node.java and Tree.java files to gradescope

addNode

public void addNode(Node<T> node) {
  if (root == null) root = node;
  else addNode(root, node);
}

private void addNode(Node<T> current, Node<T> nodeToAdd) {
  int cmp = nodeToAdd.getData().compareTo(current.getData());
  if (cmp < 0) {
    if (current.getLeft() == null) current.setLeft(nodeToAdd);
    else addNode(current.getLeft(), nodeToAdd);
  } else if (cmp > 0) {
    if (current.getRight() == null) current.setRight(nodeToAdd);
    else addNode(current.getRight(), nodeToAdd);
  }
  // cmp == 0: duplicate value, do not add
}

toString

It’s going to be easy to test adding multiple nodes if we implement toString

Here’s the public toString:

public String toString() {
  if (root == null) return "empty tree";
  return (root.getData() + " is the root\n" + toString(root)).trim();
}

Implement a private recursive toString(Node)

Depth-First Traversal (DFS)

These traverse as far down a branch as possible before backtracking:

Inorder (Left → Root → Right)

  • Visits left subtree, then root, then right subtree
  • For binary search trees, this produces values in sorted order

Preorder (Root → Left → Right)

  • Visits root first, then left subtree, then right subtree
  • Useful for creating a copy of the tree or getting prefix expressions

Depth-First Traversal (DFS)

These traverse as far down a branch as possible before backtracking:

Postorder (Left → Right → Root)

  • Visits left subtree, then right subtree, then root last
  • Useful for deleting trees or evaluating postfix expressions

Breadth-First Traversal (BFS)

Level-order

  • Visits nodes level by level, from top to bottom and left to right
  • Typically implemented using a queue (we will see more of this later)
  • Useful for finding shortest paths or level-based operations

toString

One way to implement this that I find useful for debugging (this is a preorder traversal: current node first, then left subtree, then right subtree):

private String toString(Node<T> current) {
  if (current == null) return "";

  String message = "";
  if (current.getLeft() != null) {
    message += current.getData() + " left child is " + current.getLeft().getData() + "\n";
  }
  if (current.getRight() != null) {
    message += current.getData() + " right child is " + current.getRight().getData() + "\n";
  }

  message += toString(current.getLeft());
  message += toString(current.getRight());
  return message;
}

Other methods

  • findMin
  • findMax

Before you start writing code, what is the strategy here?

Submit your Tree.java, Node.java and BST.java to gradescope – make sure toString() returns a string with all node values in-order separated by a single space

findMin

Here’s a recursive implementation, you can also implement this with a while loop:

public Node<T> findMin() {
  return findMin(root);
}

private Node<T> findMin(Node<T> current) {
  if (current == null) return null;               // empty tree
  if (current.getLeft() == null) return current;  // can't go further left
  return findMin(current.getLeft());
}

findMax

Here’s a recursive implementation, you can also implement this with a while loop:

public Node<T> findMax() {
  return findMax(root);
}

private Node<T> findMax(Node<T> current) {
  if (current == null) return null;                // empty tree
  if (current.getRight() == null) return current;  // can't go further right
  return findMax(current.getRight());
}

Search

What’s the runtime?

public Node<T> search(T value) {
  return search(root, value);
}

private Node<T> search(Node<T> current, T value) {
  if (current == null) return null;     // fell off the tree: not found
  int cmp = value.compareTo(current.getData());
  if (cmp == 0) return current;         // found it
  if (cmp < 0) return search(current.getLeft(), value);
  return search(current.getRight(), value);
}

Search runtime

\(O(\log n)\) when the tree is balanced

  • In a balanced BST the number of iterations (in our case recursive calls) equals the height of the tree.
  • The height of the tree is \(\log n\)

Worst case: \(O(n)\) (why?)

Remove

Before you start writing code, what is the strategy here?

Remove

General idea - search for node to remove and its parent.

Remove

Leaf

  • Can be removed without breaking tree

One child (two cases really, left/right)

  • Cannot be removed without breaking tree
  • Can be removed with only locally available pointers

Remove

Two children

  • Cannot be removed without breaking tree
  • Cannot be fixed with locally available pointers
  • Costs an additional O(h) (h is the height of the tree) work to find a way to fix.

Remove

BST lemon lemon guava guava lemon--guava raspberry raspberry lemon--raspberry coconut coconut guava--coconut kiwi kiwi guava--kiwi lychee lychee raspberry--lychee strawberry strawberry raspberry--strawberry avocado avocado coconut--avocado fig fig coconut--fig lime lime lychee--lime pomelo pomelo lychee--pomelo starfruit starfruit strawberry--starfruit tomato tomato strawberry--tomato null1 null2

Remove

A leaf can be removed without breaking the tree

BST lemon lemon guava guava lemon--guava raspberry raspberry lemon--raspberry coconut coconut guava--coconut kiwi kiwi guava--kiwi lychee lychee raspberry--lychee strawberry strawberry raspberry--strawberry avocado avocado coconut--avocado fig fig coconut--fig lime lime lychee--lime pomelo pomelo lychee--pomelo starfruit starfruit strawberry--starfruit tomato tomato strawberry--tomato null1 null2

Remove

Node with one child can be removed with only locally available pointers

BST lemon lemon guava guava lemon--guava raspberry raspberry lemon--raspberry coconut coconut guava--coconut null0 guava--null0 lychee lychee raspberry--lychee strawberry strawberry raspberry--strawberry avocado avocado coconut--avocado fig fig coconut--fig lime lime lychee--lime pomelo pomelo lychee--pomelo starfruit starfruit strawberry--starfruit tomato tomato strawberry--tomato null1 null2

Remove

Node with one child can be removed with only locally available pointers

BST lemon lemon coconut coconut lemon--coconut raspberry raspberry lemon--raspberry avocado avocado coconut--avocado fig fig coconut--fig lychee lychee raspberry--lychee strawberry strawberry raspberry--strawberry lime lime lychee--lime pomelo pomelo lychee--pomelo starfruit starfruit strawberry--starfruit tomato tomato strawberry--tomato null1 null2

Remove

Node with two children

BST lemon lemon coconut coconut lemon--coconut raspberry raspberry lemon--raspberry avocado avocado coconut--avocado fig fig coconut--fig lychee lychee raspberry--lychee strawberry strawberry raspberry--strawberry lime lime lychee--lime pomelo pomelo lychee--pomelo starfruit starfruit strawberry--starfruit tomato tomato strawberry--tomato null1 null2

Remove

Node with two children – replace node to remove data with min to the right data (or max to the left data)

BST lemon lemon coconut coconut lemon--coconut raspberry raspberry lemon--raspberry avocado avocado coconut--avocado fig fig coconut--fig lychee lychee raspberry--lychee strawberry strawberry raspberry--strawberry lime lime lychee--lime pomelo pomelo lychee--pomelo starfruit starfruit strawberry--starfruit tomato tomato strawberry--tomato null1 null2

Remove

Node with two children – replace node to remove data with min to the right data (or max to the left data)

BST lemon lemon coconut coconut lemon--coconut starfruit starfruit lemon--starfruit avocado avocado coconut--avocado fig fig coconut--fig lychee lychee starfruit--lychee strawberry strawberry starfruit--strawberry lime lime lychee--lime pomelo pomelo lychee--pomelo null2 strawberry--null2 tomato tomato strawberry--tomato null1

Gradescope Exercise

Complete gradescope’s exercise on BST node removal

Remove – steps

  • find the node to remove and its parent
  • count how many children the node to remove has
    • 0 children – set parent.left/right to null
    • 1 child – set parent.left/right to the “orphan” child
    • 2 children – find the min of the right subtree (the replacement), copy its data into the node to remove, then remove the replacement node (it has at most one child, a right child)
  • if the node to remove is the root, there is no parent – update root instead

Submit your solution to gradescope

remove implementation

public void remove(T value) {
        // find node to remove and its parent
        Node<T> parent = null;
        Node<T> current = root;
        boolean found = false;
        while (!found && current != null) {
            int cmp = value.compareTo(current.getData());
            if (cmp == 0) found = true;              // found it
            else {
                parent = current;
                if (cmp < 0) current = current.getLeft();
                else current = current.getRight();
            }
        }
        if (current != null) remove(parent, current); 
}

private void remove(Node<T> parent, Node<T> nodeToRemove) {
  // count number of children
  int children = 0;
  Node<T> child = null;
  if (nodeToRemove.getLeft() != null) {
    children++;
    child = nodeToRemove.getLeft();
  }
  if (nodeToRemove.getRight() != null) {
    children++;
    child = nodeToRemove.getRight();
  }

  if (children <= 1) {
    // 0 children: child is null, 1 child: child has no sibling
    if (parent == null) root = child;
    else if (parent.getLeft() == nodeToRemove) parent.setLeft(child);
    else parent.setRight(child);
  } else {
    // 2 children: find min of the right subtree (and its parent)
    Node<T> replacementParent = nodeToRemove;
    Node<T> replacement = nodeToRemove.getRight();
    while (replacement.getLeft() != null) {
      replacementParent = replacement;
      replacement = replacement.getLeft();
    }
    // copy replacement data up
    nodeToRemove.setData(replacement.getData());
    // then unlink the replacement node
    // replacement (node we are to remove) might have a right child
    if (replacementParent == nodeToRemove) replacementParent.setRight(replacement.getRight());
    else replacementParent.setLeft(replacement.getRight());
  }
}

Recap

  • What is a binary search tree?
  • How do you traverse a binary search tree?
  • How do you search a binary search tree?
  • How do you add to a binary search tree?
  • How do you remove from a binary search tree?
  • What is the runtime of these operations?

BST Implementation

The complete BST class, with every method we wrote today:

public class BST<T extends Comparable<T>> implements Tree<T>{
    private Node<T> root;

    public BST() { root = null; }

    public Node<T> getRoot() { return root; }

    // ---------- add ----------
    public void addNode(Node<T> node) {
        if (root == null) root = node;
        else addNode(root, node);
    }

    private void addNode(Node<T> current, Node<T> nodeToAdd) {
        int cmp = nodeToAdd.getData().compareTo(current.getData());
        if (cmp < 0) {
            if (current.getLeft() == null) current.setLeft(nodeToAdd);
            else addNode(current.getLeft(), nodeToAdd);
        } else if (cmp > 0) {
            if (current.getRight() == null) current.setRight(nodeToAdd);
            else addNode(current.getRight(), nodeToAdd);
        }
        // cmp == 0: duplicate value, do not add
    }

    // ---------- toString (preorder) ----------
    public String toString() {
        if (root == null) return "empty tree";
        return (root.getData() + " is the root\n" + toString(root)).trim();
    }

    private String toString(Node<T> current) {
        if (current == null) return "";

        String message = "";
        if (current.getLeft() != null) {
            message += current.getData() + " left child is " + current.getLeft().getData() + "\n";
        }
        if (current.getRight() != null) {
            message += current.getData() + " right child is " + current.getRight().getData() + "\n";
        }

        message += toString(current.getLeft());
        message += toString(current.getRight());
        return message;
    }

    // ---------- findMin / findMax ----------
    public Node<T> findMin() {
        return findMin(root);
    }

    private Node<T> findMin(Node<T> current) {
        if (current == null) return null;               // empty tree
        if (current.getLeft() == null) return current;  // can't go further left
        return findMin(current.getLeft());
    }

    public Node<T> findMax() {
        return findMax(root);
    }

    private Node<T> findMax(Node<T> current) {
        if (current == null) return null;                // empty tree
        if (current.getRight() == null) return current;  // can't go further right
        return findMax(current.getRight());
    }

    // ---------- search ----------
    public Node<T> search(T value) {
        return search(root, value);
    }

    private Node<T> search(Node<T> current, T value) {
        if (current == null) return null;     // fell off the tree: not found
        int cmp = value.compareTo(current.getData());
        if (cmp == 0) return current;         // found it
        if (cmp < 0) return search(current.getLeft(), value);
        return search(current.getRight(), value);
    }

    // ---------- remove ----------
    public void remove(T value) {
        // find node to remove and its parent
        Node<T> parent = null;
        Node<T> current = root;
        boolean found = false;
        while (!found && current != null) {
            int cmp = value.compareTo(current.getData());
            if (cmp == 0) found = true;              // found it
            else {
                parent = current;
                if (cmp < 0) current = current.getLeft();
                else current = current.getRight();
            }
        }
        if (current != null) remove(parent, current);  
    }

    private void remove(Node<T> parent, Node<T> nodeToRemove) {
      // count number of children
      int children = 0;
      Node<T> child = null;
      if (nodeToRemove.getLeft() != null) {
        children++;
        child = nodeToRemove.getLeft();
      }
      if (nodeToRemove.getRight() != null) {
        children++;
        child = nodeToRemove.getRight();
      }

      if (children <= 1) {
        // 0 children: child is null, 1 child: child has no sibling
        if (parent == null) root = child;
        else if (parent.getLeft() == nodeToRemove) parent.setLeft(child);
        else parent.setRight(child);
      } else {
        // 2 children: find min of the right subtree (and its parent)
        Node<T> replacementParent = nodeToRemove;
        Node<T> replacement = nodeToRemove.getRight();
        while (replacement.getLeft() != null) {
          replacementParent = replacement;
          replacement = replacement.getLeft();
        }
        // copy replacement data up
        nodeToRemove.setData(replacement.getData());
        // then unlink the replacement node
        // replacement (node we are to remove) might have a right child
        if (replacementParent == nodeToRemove) replacementParent.setRight(replacement.getRight());
        else replacementParent.setLeft(replacement.getRight());
      }
    }
}

BST operations runtime

When tree height \(h\) is \(\log n\) for (near) balanced tree.

  • Search, Insert, Delete: O(log n) - when the tree is reasonably balanced
    • Worst case: O(n) - when the tree degenerates into a linked list (all nodes in a single chain)
  • Find Minimum/Maximum: O(log n) - when the tree is reasonably balanced
    • Worst case: O(n)
  • Traversal (inorder, preorder, postorder): always O(n) - must visit every node