next up previous index
Next: Java implementation Up: Data Structures Previous: Doing it yourself   Index


Binary Search Trees

An important linked data structure is the binary tree. This has the following property
(B)
A binary tree is either empty, or else consists of some data item together with a left and right descendant binary tree.
One of the most useful types of binary tree is a binary search tree, for example

\begin{picture}(200,190)(-70,0)
\put(0,180){\makebox(0,0){21}}
\put(-60,120){\...
...){20}}
\put(-12,12){\line(2,3){20}}
\put(52,12){\line(-2,3){20}}
\end{picture}
(S)
A binary search tree is a binary tree in which the value stored at each node of the tree is greater than the values stored in its left subtree and less than the values stored in its right subtree.
Binary search trees can be constructed with other types of data. All that matters is that the data items can be compared with regard to order.

If we want to find out whether a given object is present in a binary search tree, we can proceed as follows. Suppose the item is the number 39. Beginning at the root of the tree, we see that 39 is greater than 21, so that if 39 is present in the tree, it must occur in the right hand sub-tree because of the (S) property. Since 39 is less than 40, it must occur in the left-hand sub-tree of the tree rooted at 40. We next compare 39 with 31, move to the right and finally compare 39 with 35. Since 39 is greater than 35, it must occur in the right hand sub-tree of the tree rooted at 35, if it occurs at all. But the right-hand sub-tree at 35 is empty, and nothing occurs in the empty tree. We have therefore established that 39 is not present in the tree.

Note that all the comparisons made occurred on a path through the tree, beginning at the root and ending at one of the leaves. For efficiency, binary search trees are much more useful if they are balanced. This means that the path lengths from the root node to each of the leaf nodes are roughly the same. The tree shown above is not as well balanced as it could be. The same data could just as well be stored in the balanced tree


\begin{picture}(200,135)(-100,0)
\put(0,120){\makebox(0,0){31}}
\put(-60,60){\...
...{20}}
\put(-28,12){\line(-2,3){20}}
\put(92,12){\line(-2,3){20}}
\end{picture}
There are several algorithms for re-balancing binary search trees. These will be discussed in a later course.



Subsections
next up previous index
Next: Java implementation Up: Data Structures Previous: Doing it yourself   Index
Peter Williams 2005-06-07