ArticlePDF Available

A Note on Enumerating Binary Trees



Gary Knott has presented algorithms for computing a bljectton between the set of binary trees on n nodes and an mmal segment of the posmve integers Rotem and Varol presented a more complicated algorithm that computes a different bljectmn, clmmmg that thetr algorithm is more efficient and has advantages ff a sequence of several consecutive trees is reqmred A modlficatmn of Knott's algorithm that ts simpler than Knott's and as effioent as Rotem and Varol's is presented Also given is a new hnear-time algorithm for transforming a tree mto ~ts successor m the natural ordering of binary trees
A Note on Enumerating Binary Trees
Umverstty of Wtsconsm, Madtson, Wtsconsm
ABSTRACT Gary Knott has presented algorithms for computing a bljectton between the set of binary trees on n
nodes and an mmal segment of the posmve integers Rotem and Varol presented a more complicated algorithm
that computes a different bljectmn, clmmmg that thetr algorithm is more efficient and has advantages ff a
sequence of several consecutive trees is reqmred A modlficatmn of Knott's algorithm that ts simpler than Knott's
and as effioent as Rotem and Varol's is presented Also given is a new hnear-time algorithm for transforming a
tree mto ~ts successor m the natural ordering of binary trees
KEY WORDS AND PHRASES binary trees, permutations, generators, enumeratmn, combmatortcs, stack-sortable
CR CATEGORIES 3 79, 5.39
1. Introduction
Gary Knott [1] has pubhshed algorithms for computing a bljection
from the set of
binary trees with n nodes to an initial segment of the integers and for computing
Rank -1.
His method for computing
Rank -~
revolves generating certain permutations of {1, 2 .....
n} called
tree permutattons,
which are m one-to-one correspondence with the binary trees
and from which the binary trees may be easily constructed. Rotem and Varol [2] propose
an alternative technique for generating the trees. Instead of constructing the tree permu-
tations (which they call
stack-sortable permutattons)
directly, they construct the
of these permutations, which are sequences of nonnegative integers called
They show that the ballot sequences may be generated in lexicographlc order
and present a clever and efficient algorithm for converting the ballot sequences into trees.
In this note, we correct some misconceptions put forth by Rotem and Varol and describe
modifications of Knott's algorithms that map
between trees and Integers, as well
as a new algorithm that transforms a given tree to the next one in sequence.
In comparing their technique to Knott's, Rotem and Varol concede that their method
does not generate the trees in the "natural" order, but claim two advantages: (1) They say
their technique is more efficient, since it is "well known" that the mapping of permutations
to trees requires
O(n 2)
operations In the worst case for trees with n nodes In contrast, their
method requires only
log n) operations to create an n-node tree, provided a table ofn 2
values has been precomputed. They also imply a similar advantage for their calculaUon of
(2) They point out that a ballot sequence may be efficiently generated from the
previous one and converted to a tree, yielding a technique for generating a sequence of
trees. They claim that using Knott's method "to generate k trees corresponding to
consecutive permutations would require the transformation of k ind~ces, since there is no
Permission to copy without fee all or part of this materml ~s granted prowded that the copies are not made or
dtstnbuted for direct commercial advantage, the ACM copyright notice and the utle of the pgbhcauon and its
date appear, and nottce is given that copying is by permission of the Assooatlon for Computing Machinery To
copy otherwtse, or to repubhsh, reqmres a fee and/or specific permission
This research was supported m part by the Umted States Army under Contract No DAAG29-75-C-0024
Authors' address Computer Soences Department, Umverslty of W~sconsm, 1210 West Dayton Street, Madison,
Wl 53706
© 1980 ACM 0004-5411/80/0100-0003 $00 75
Journal of the Assooatlon for Computing Maclunery, Vol 27, No I, January 1980, pp 3-5
simple way of deriving stack-sortable permutations in their order corresponding to the
natural order of trees" [ 1, p. 404].
With regard to the first claim, we point out that whereas the mapping of an
permutation to the corresponding tree may take O(n 2) operations, a
permutation may
be converted to a tree in
operations, due to its special properties. Rather than prove
this result here, however, we present a modification of Knott's algorithm that translates
directly from indices to trees.
With regard to the generation of sequences of trees, we show how to transform a tree to
the next one in the natural order by an algonthm that works directly on the tree and
2. Definitions
A binary tree
Tis either a
null tree
or consists of a node called the
and two binary trees
In the former case, the
of T is zero; m the latter case,
Size(T) ffi 1 + Size(Left(T)) + Size(Right(T)).
We will often identify a tree with its root.
Define a relation on trees by T~ < T2 if and only if one of the foUowmg condmons hold:
Size(T1) < Size(T2)
Size(T 0 ffi Size(T2)
Left(T 0 < Left(T2)
Size(T1) = Size(T2)
Left(T~) ffi Left(T2)
Right(T1) < Right(T2).
This ordering is called the
ordering of trees. Let { T~, T2 ..... Tnn } be the sequence
of all trees of size n, ordered by the natural ordering. It is well known that B~ is the
Catalan number
Rank(TO = i, Rank-nO, n) = T,,
Next(TJ = T,÷i,
and let
denote the
depicted in Figure l(a). The
tree of size n Is
depicted in Figure l(b).
3. Algorithms
This section contains algorithms for computing
Next, Rank,
Rank -1.
We assume that
T is represented by a pointer to a structure containing the two trees
as well as
The size is provided for efficient Implementation of
First a table of Catalan numbers should be prepared according to the recurrence cited
Bn = 4Bn-1
attempts to transform T to its successor in the natural ordenng. It falls tf T is
(a) (b)
FIG 1 The first and last trees with n nodes
A Note on Enumerating Bmary Trees 5
the last tree of size n. Otherwise, an algorithm follows directly from the definition of the
natural order: The successor of T may be formed by attempting first to transform T's right
subtree to its successor. (This subproblem is solved recursively ) If T's right subtree has no
successor, then that tree is reset to the first tree of its size, and the left subtree is transformed
to its successor (This subproblem is also solved recursively.) If both the subtrees are the
last trees of their sizes, then one node is transferred from the right to the left and both
subtrees are remitialized.
The computation time for a call to
exclusive of calls to
and recurslve calls to
is bounded by a constant.
may be calculated m time proportional to n.
Finally, a call of
gives rise to at most one recursive call for each node in T.
is calculated in time
where n =
Rank-l(i, n)
may be calculated by essentially the same counting argument as the one
used by Knott. Let Gkn denote the number of trees w~th n nodes whose left subtree has k
nodes. As Knott points out, Gkn =
Then the size of the left subtree of T, is the
largest integer I such that Sin = ~k_~t Gkn < i. As Rotem and Varol point out, this value may
be calculated quickly by precomputmg some values of Sin and using binary search to find
the largest
less than i. The complexity of finding the size of both subtrees is then
O(log l) _< O(log n). The left and right subtrees of T, may be calculated recursively as
Rank-I([i/BrJ, l)
respectwely, where r = n - l - 1 is the size of
the right subtree.
Exclusive of recurswe invocations,
Rank-l(i, n)
is calculated in time O(log n). Since each
recursive call of
generates one node of the resulting tree, the total time is bounded
log n).
may be computed by counting the number of trees preceding T in the natural
ordering. They may be divided into three classes: those T' for which
Size(Left(T')) <
those for which
Stze( Left( T') ) = Size(Right(T))
Left( T') < Left(T),
those for which
Left(T') = Left(T)
Right(T') < Right(T).
Let n =
and let l
and r be the sizes and j and k the ranks of the left and right subtrees of T. Then the first
class contains St~ trees, the second class contains (j - l)Br trees, and the third class
contains k - 1 trees. The rank of the entire tree is one greater than the sum of these three
The calculation of
requires constant time to find the sizes of its subtrees (since
we are assuming the informaton is stored in their roots) m addmon to one recursive call
for each node of T. Thus the running Ume of
Rank Is O(n).
4. Conclusions
We have presented straightforward and efficient algorithms for computing the rank of a
tree m the natural ordering of binary trees of a given size and for constructing the tree with
a given rank. We have also presented a new linear algorithm that transforms a tree to its
successor in the natural ordenng.
1 KNOTT, G D A numbering system for binary trees
Comm ACM 20,
2 (Feb 1977), 113-115
2 ROTEM, D, AND VAROL, Y L Generation of binary trees from ballot sequences. J.
ACM 25,
3 (July 1978),
TheArt of Computer Programming, Vol 1 FundamentalAlgorlthms
Addison-Wesley, Reading,
Mass, 1973
Journal of the Assocmuon for Computing Machinery, Vol 27, No I, January 1980
... Several authors [24,30,29,33,41] have examined the problem of randomly generating ordered binary trees using various forms of ranking and unranking algorithms. These algorithms were not suited to our purposes because of the sparseness of ordered trees and also because the time required to generate each tree is 0(N log N) for iV-node trees INTRODUCTION ...
... Exhaustive generation of certain combinatorial objects has always been of great interest for computer scientists [14,22,24,29]. In general, generation of combinatorial structure problem is to construct all possible combinatorial structures of a particular kind in a certain order [12]. ...
In this paper, we present a new generation algorithm with corresponding ranking and unranking algorithms for (k, m)-ary trees in B-order. (k, m)-ary tree is introduced by Du and Liu. A (k, m)-ary tree is a generalization of k-ary tree, whose every node of even level of the tree has degree k and odd level of the tree has degree 0 or m. Up to our knowledge no generation, ranking or unranking algorithms are given in the literature for this family of trees. We use Zaks’ encoding for representing (k, m)-ary trees and to generate them in B-order. We also prove that, to generate (k, m)-ary trees in B-order using this encoding, the corresponding codewords should be generated in reverse-lexicographical ordering. The presented generation algorithm has a constant average time and O(n) time complexity in the worst case. Due to the given encoding, both ranking and unranking algorithms are also presented taking O(n) and \(O(n\log n)\) time complexity, respectively.
Enumeration is an important aspect for combinatorial properties of binary trees. Traditional solutions for enumerating binary trees are expressed by algorithms and most of them are recursive. In this paper, we give our solutions by iterative formulas for enumerating binary trees. Iterative algorithms can be obtained easily based on the iterative formulas for enumerating binary trees, and the iterative algorithms can be guaranteed to be correct.
The shapes of binary trees can be encoded as permutations having a veryspecial property. These permutations are tree permutations, or equivalently they avoidsubwords of the type 231. The generation of binary trees in natural order correspondsto the generation of these special permutations in the lexicographic order. In this pa-per we use a stringologic approach to the generation of these special permutations:decompositions of essential parts into the subwords having staircase shapes. A givenpermutation differs from the next one with respect to its tail called here the workingsuffix. Some new properties of such working suffixes are discovered in the paper andused to design effective algorithms transforming one tree permutation into its succes-sor or predecessor in the lexicographic order. The algorithms use a constant amountof additional memory and they look only at those elements of the permutation whichbelong to the working suffix. The best-case, average-case and worst-case time complex-ities of the algorithms are O(1), O(1), and O(n) respectively. The advantages of ourstringologic approach are constant time and iterative generation, while other knownalgorithms are usually recursive or not constant-memory ones.
In literature, many methods have been presented for enumerating binary trees (full binary trees) and regular k-ary trees, while no one for enumerating arbitrary trees or arbitrary k-ary trees. It is proposed in 1997 using a context-free grammar GBT (GFBT) to code binary trees (full binary trees) for enumerating them. In this paper, we use another grammar GT (GTk) to code arbitrary trees (arbitrary k-ary trees) for enumerating them. The properties of words of ℒn(GT) (ℒn(GTk)) are discussed in depth, including necessary and sufficient conditions for a word, prefix and suffix of ℒn(GT) (ℒn(GTk)), and efficient algorithms are given and analyzed for the enumeration of words of ℒn(GT) (ℒn(GTk)).
A set of maximal non-intersecting diagonals can decompose a polygon into triangles, and the edges and diagonals can be converted into the external and internal nodes of a strictly binary tree. This paper gives algorithms to generate all types of triangulations and triangulations at random. Based on that, this paper gives an algorithm to generate strictly binary trees at random. The experimental results show that the numbers of various shapes of strictly binary trees generated are nearly equal. The algorithm to generate strictly binary trees at random can be transformed to the algorithm to randomly generate binary trees.
Several combinatorial and other programs deal with the structure (or the shape) of binary trees paying no attention to the data possibly maintained by the tree. For such programs it is useful to represent the structure without pointers and records. This paper surveys such representations. Especially, we concentrate on different ways of representing the structure of a binary tree by using a sequence of integers.
A simple and elegant algorithm for converting a given inorder-postorder sequence to its corresponding binary tree is derived. This conversion algorithm is more efficient than Semba's conversion algorithm, as revealed in a performance test. Coupled with an efficient algorithm for generating all inorder-postorder sequences, the conversion algorithm can be used for generating all binary trees. The resulting algorithm is more efficient than that of Semba for performing the same task.
2.1.1. Introductory Remarks. In this chapter, we describe an approach used in our book for the representation of algorithms and analysis of their correctness and complexity. We also consider basic classes of algorithms used for the realization of traversais of graphs and trees (Section 2.2) and construction of trees with desired properties (Section 2.3).
Full-text available
An efficient algorithm for generating and indexing all shapes of n-noded binary trees is described The algorithm is based on a correspondence between binary trees and the class of stack-sortable permutations. together with a representation of such permutatmns as ballot sequences Justification for the related procedures is given, and their efficiency estabhshed by comparison to other approaches
Some recent work on the development of general-purpose computer-based statistical and data processing capabilities for handling multidimensional arrays of data is presented. Attention is first given to some of the general problems of multidimensional ...
  • D E Theart Knuth
  • Of
KNUTH, D E TheArt of Computer Programming, Vol 1 FundamentalAlgorlthms Addison-Wesley, Reading, Mass, 1973