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
A Binary Search Tree (BST) is a linked structure where:
Repeated values can be handled differently, we will be implementing a strict BST (disallow duplicates).
Each node has at most two children
Everything in a left subtree is smaller than its parent node
Everything in a right subtree is larger than its parent node
We will look at 5 functions:
Data in Node that we want to add: 7
What do we have to do to add Node 7 to the right spot?
Compare value to be added to root
7 is less than 10, so our next comparison is with the root of the left subtree
7 is greater than 5, so our next comparison is with the root of the right subtree
7 is less than 8, so our next comparison is with the root of the left subtree
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.
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)
In the worst case you get O(n) operations – how? Add 90 to tree:
In the worst case you get O(n) operations – how? Add 80 to tree:
In the worst case you get O(n) operations – how? Add 79 to tree:
In the worst case you get O(n) operations – how? Add 65 to tree:
In the worst case you get O(n) operations – how? Add 42 to tree:
In the worst case you get O(n) operations – how? Add 26 to tree:
In the worst case you get O(n) operations – how?
The tree is now a linked list: search takes O(n)
The solution to this problem is Self-balancing Binary Search Trees (BBSTs).
We will not be implementing a self-balancing binary search tree in class.
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())
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.
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;
}
}getRoot())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) {};
}This recursive method should be private.
private void addNode(Node<T> current, Node<T> nodeToAdd)
Strategy:
compareTo)addNode recursively with left/right child as current nodeTree<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
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
}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)
These traverse as far down a branch as possible before backtracking:
Inorder (Left → Root → Right)
Preorder (Root → Left → Right)
These traverse as far down a branch as possible before backtracking:
Postorder (Left → Right → Root)
Level-order
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;
}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
Here’s a recursive implementation, you can also implement this with a while loop:
Here’s a recursive implementation, you can also implement this with a while loop:
Before you start writing code, what is the strategy here?
Submit your Tree.java, Node.java and BST.java to gradescope
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);
}\(O(\log n)\) when the tree is balanced
Worst case: \(O(n)\) (why?)
Before you start writing code, what is the strategy here?
General idea - search for node to remove and its parent.
Leaf
One child (two cases really, left/right)
Two children
A leaf can be removed without breaking the tree
Node with one child can be removed with only locally available pointers
Node with one child can be removed with only locally available pointers
Node with two children
Node with two children – replace node to remove data with min to the right data (or max to the left data)
Node with two children – replace node to remove data with min to the right data (or max to the left data)
nullroot insteadSubmit your solution to gradescope
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());
}
}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());
}
}
}When tree height \(h\) is \(\log n\) for (near) balanced tree.