While we can replace linear search with binary search on sorted arrays to improve
how many comparisons we have to do, this is not so straightforward with linked lists, even if sorted. The
structure of the linked list requires linear traversal, rather than the random access required for binary search.
Instead, we will store sorted data differently so that finding elements can be much more efficient. Each node of a
binary tree contains some data (in our case, an integer) and two branches:
//BST
// - null (for an empty tree)
// - a BST object (for a tree node)
/**
* INVARIANT: the values stored in all descendants
* on the left are <= v
* the values stored in all descendants
* on the right are >= v
*/
class BST {
BST(int v, BST l, BST r) {
value = v;
left = l;
right = r;
}
int value;
BST left;
BST right;
}
value is the integer at this node.
left is a tree of integers in the tree that are less than or equal to the value in the current node (Null if there are none).
right is a tree of integers in the tree that are greater than or equal to the value in the current node (Null if there are none).
The BST has a Data Invariant to ensure the conditions on the values stored in the left and right children.