Given two things: a list of L items and a linear order ≺ on them.
A binary search tree for L and ≺ is a binary tree in which every vertex is labelled with an item from L such that we have:
the label of each vertex:
is ≺-greater than the labels of all vertices in the left subtree
is ≺-less than the labels of all vertices in its right subtree
every path in the tree be compatible with the order of listing:
We are given a list L of items, and a linear order ≺ on them.
We go through each member of the list, from left to right:
First item: becomes our root
Comparing: We take the next item in the list, and first compare it with the labels of the ‘old’ vertices already in the list, starting from the root then:
moving to the left: if the new item is ≺-less than the label of the respective ‘old’ vertex, if this ‘old’ vertex has a left child, or:
moving to the right: if the new item is ≺-greater than the label of the respective ‘old’ vertex, if this ‘old’ vertex has a right child.
Adding:
When the new item is ≺-less than the label of an ‘old’ vertex and the vertex has no left child, insert a new left child to the ‘old’ vertex and label it with the new item.
When the new item is ≺-larger than the label of an ‘old’ vertex and the vertex has no child, then we insert a new right child to the ‘old’ vertex and label it with the new item.
Example BST
Build a binary search tree for the following list of words using the lexicographical order ≺.
Finally, we take psychology, compare it with mathematics, move to the right, compare it with physics, move to the right then compare it with zoology, psychology≺zoology, hence create a new left child:
Say we had to add a new word, chemistry, to our BST.
How many comparisons do we need to locate or find it?
In this case, it’s just 2. We compare it with mathematics, move left, compare it with geography.
As chemistry≺geography and geography has no left child, we know that chemistry is not in the tree.
We can create a new left child and label it as such.