Listing and Counting Subtrees of Equal Size of a Binary Tree

Our objects of study are rooted ordered binary trees and their subtrees. In particular, we only treat subtrees which share the root with their parent tree. A tree or a subtree with exactly k nodes are simply called a k-tree or a k-subtree, respectively. The purpose of this paper is to present an efficient algorithm which, given a tree and a value k, lists and enumerates all k-subtrees of the tree. There have been given many algorithms which generate all k-trees in some order [1,3,4,6-111. Ruskey [5] gave an algorithm which, given a tree, lists all subtrees of the tree in an order independent of the numbers of nodes of the subtrees. The strategy of our algorithm is simple, and can be summarized, as follows. (1) Generate all k-trees in some order, for each of them test whether it can be embedded in the given tree, and list the k-trees which have passed this test. (2) In the above, do not test the embeddability after each k-tree is completely produced, but rather do the production and test in parallel. Thus one knows the impossibility of embedding as early as possible. (3) Represent all the trees by ‘inorder-preorder sequences’. These sequences are certain permutations of the sequence 1, 2,. . . , k. The set of inorder-preorder sequences exactly corresponds to that of ordered binary trees. We do not treat here transformation algorithms between inorder-preorder sequences and other representations of trees. In this paper, first a naive algorithm is presented which lexicographically generates all these sequences of length k in average constant time per sequence. Then using it an algorithm is presented which lists and enumerates all k-noded subtrees of a given rooted ordered binary tree. As an application of the algorithm, the numbers of k-noded binary trees of height h, 0 < h < k 1, were calculated with the aid of an computer in the range of 1 < k < 13.