334 Intermediate C Programming
FIGURE 20.13: Five different shapes for the pre-order traversals of binary search trees
storing 1, 2, and 3. (a) < 1, 2, 3 >, (b) < 1, 3, 2 >, (c) < 2, 1, 3 >, (d) < 3, 2, 1 >, (e)
< 3, 1, 2 >.
numbers as well. As illustrated by the example above, s(n) ≤ n! because there are n! possible
permutations of 1, 2,..., n. If n > 2, s(n) must be smaller than n!. We have already seen
that s(3) = 5 ≤ 3! = 6
Below is a proof that s(n) defines the sequence of Catalan numbers. Suppose a se-
quence of numbers < a
1
, a
2
, a
3
, ...a
n
> is a particular permutation of 1, 2, ..., n and the
sequence is stack-sortable. Any prefix < a
1
, a
2
, a
3
, ...a
k
>, k < n must be stack-sortable.
Suppose a
i
(1 ≤ i ≤ n) is n (the largest number in the entire sequence). Then the sequence
< a
1
, a
2
, a
3
, ...a
n
> can be divided into three parts:
< a
1
, a
2
, ..., a
i−1
> a
i
= n < a
i+1
, a
i+2
, ..., a
n
>
What is the condition that makes a sequence stack-sortable? Section 15.4 explained
that max(a
1
, a
2
, ..., a
i−1
) must be smaller than min(a
i+1
, a
i+2
, ..., a
n
). Therefore, the first
sequence must be a permutation of 1, 2, ..., i − 1 and the second sequence must be a
permutation of i, i + 1, ..., n − 1. Moreover, the two sequences < a
1
, a
2
, ..., a
i−1
> and
< a
i+1
, a
i+2
, ..., a
n
> must also be stack-sortable; otherwise, the entire sequence cannot be
stack-sortable. Therefore the entire sequence includes two stack-sortable sequences divided
by a
i
= n. By definition, there are s(i − 1) stack-sortable permutations of 1, 2, 3, ..., i − 1.
There are s(n −i) stack-sortable permutations of i, ..., n −1. The permutations in these two
sequences are independent so there are s(i − 1) × s(n − i) possible permutations of the two
sequences. The value of i is between 1 and n. When i is 1, the first value in the sequence is
n and this corresponds to the tree in which the root has no left child. When i is n, the last
value is n and this corresponds to the tree in which the root has no right child. Thus, the
total number of stack-sortable permutations is:
s(n) =
n
X
i=1
s(i − 1) × s(n − i) =
n−1
X
i=0
s(i) × s(n − i − 1). (20.2)
This is the Catalan number.