Quick Index
Here is a video to go along with this page (BST algorithms).

Overview


Searching and inserting in a binary search tree are done in a similar way.

Duplicates



Element Comparison


Left or Right


What Are We Comparing?

The simplest approach is to require that all elements are of type Comparable. This approach is limited in that a comparable only supports one sort.

The problem with that solution is that for many objects, we'll want to sort in different ways, e.g. by id, name, and address, etc.

We'll utilize functional programming to add this flexibility.

Key?

In the materials, we'll often see that we search for a given element with a given element. E.g. search for an employee object given an employee object.

Another approach that is more intuitive is to search by a key. Using generics, we define the key to be any type. As an example let's say we have different search trees that support these keys (for an Employee):


Searching


A search comparison is used that has inputs of the search key and the current node's data.

We start the search at the tree root node. It becomes the "current" node in the search.

The search comparison drives the next step:

Search Comparison Result (Integer)Action
negativeContinue search to left
zeroMatch found, return current node's data
positiveContinue search to right


We continue the search until:


A search efficiency is good [O(log N)] if the tree is well balanced.

Duplicates

If a tree allows duplicates, then the first match is returned

Search Algorithm References:


Insertion (Add) Algorithm


The insertion algorithm is similar to the search algorithm. We search for the insertion position and insert the new child as a leaf.

Also see "Duplicates" above.

Insertion Algorithm References: