Next: Printing the nodes of
Up: Binary search trees
Previous: Checking whether a given
  Contents
We have already seen an example of an inductive definition over trees.
Here are another two, corresponding to notions that we have already
discussed:
size(EmptyTree) = 0
size(MkTree(v,l,r)) = 1 + size(l) + size(r)
height(EmptyTree) = -1
height(MkTree(v,l,r)) = 1 + max(height(l),height(r))
You may wish to pause to think why we have decided to define the
height of an empty tree to be -1 rather than 0. Sometimes it is
necessary to establish some properties of trees such as
This is intended to hold for all binary trees. Since there are
infinitely many trees, how could we possibly prove this? The answer
lies in the fact that, although there are infinitely many trees, there
are only two rules for creating trees, as we have seen:
- (base case)
EmptyTree is a tree.
- (induction step) If
v is a value and l and
r are trees then MkTree(v,l,r) is a tree.
Thus, each tree is obtained by starting from the base case and then
applying the induction step finitely many times. This gives rise to
the following proof rule, which plays a key rôle in correctness
proofs of algorithms that manipulate trees:
Induction principle: In order to prove that a property holds
for all binary trees, show that
- (base case) it holds for the empty tree
EmptyTree, and
- (induction step) it holds for the tree
MkTree(v,l,r)
whenever it holds for given trees l and r.
It can be proved by induction that
This is left as an exercise. We now prove by induction that
The base case is easy:
The induction step is not hard either:
- Assume that we are given trees
l and r such that
- We have to conclude that, no matter what
v is,
We do this as follows.
- Combining the two equations (1) and (2), we get
- Using this and the fact that
we conclude that
- Adding one to each side of the inequality, we get
- By the above definitions of height and size, we conclude
that
as we wished to conclude.
Next: Printing the nodes of
Up: Binary search trees
Previous: Checking whether a given
  Contents
Martin Escardo
2005-01-11