| Overall Reading | |
|---|---|
| Brookshear: | Ch. 7.5 |
Outline:
Let's view an example, such as that of Figure 7.21 (p. 347 of [Br]) as follows. We can put the 'middle' entry at the root of the tree, with all entries from the first half of the list stored recursively in the "left" subtree of the root. Similarly, all entries with values beyond the 'middle' value are stored recursively in the "right" subtree.
The binary search tree properties are defined precisely so that they support the search operation.
procedure BinarySearch(Tree, TargetValue)
assign CurrentPointer the value in the root pointer of Tree
assign Found the value "false"
while (Found is "false" and CurrentPointer is not NIL) do
[
case 1: TargetValue = current node's value
(assign Found the value "true")
case 2: TargetValue < current node's value
(assign CurrentPointer the value in
current node's left child pointer)
case 3: TargetValue > current node's value
(assign CurrentPointer the value in
current node's right child pointer)
]
Printing the names in alphabetical order does not seem as straightforward as when using a linked list. However, it can be very straightforward if we think recursively.
procedure PrintTree(Tree)
if (Tree is not empty) then
[
apply PrintTree to the root node's left subtree
print the name at the root
apply PrintTree to the root node's right subtree
]
Let's try to walk through the execution on an example, recalling how
recursion works from Ch. 4.5 of [Br].
Finally, we can insert new items into an existing binary search tree as follows. To find a proper place to insert the name, start at the root and move down the tree, as if performing a search for the new name.
Since the entry is new, the unsuccessful search will eventually reach the bottom of the tree. We can properly insert the new item as the left or right child of the point where the search ended. (intuitively, this is the correct place to put it because it is where a search for the new name would look for it)
Again, we can walk through an example, such as that of Figure 7.25 (p. 350 of [Br])
Aside: If many items get inserted in one section of the tree, we no longer have the perfect correspondance between the structure of the tree and the behavior of the binary search algorithm. That is, our tree may become unbalanced. In practice, either we can hope that insertions do not drastically unbalance our tree or we can take additional steps to alter our tree at certain points to restore the balance.