Newsgroups: comp.lang.scheme
Path: cantaloupe.srv.cs.cmu.edu!bb3.andrew.cmu.edu!newsfeed.pitt.edu!gatech!newsfeed.internetmci.com!nntp-hub2.barrnet.net!venus.sun.com!wnoc-sfc-news!kogwy!math-keio!mad
From: mad@math.keio.ac.jp (MAEDA Atusi)
Subject: Re: Counting binary trees
In-Reply-To: emartin@schemers.COM's message of 9 May 1996 09:35:14 -0400
Message-ID: <MAD.96May10212329@tanzanite.math.keio.ac.jp>
Sender: news@math.keio.ac.jp
Nntp-Posting-Host: tanzanite
Reply-To: mad@math.keio.ac.jp
Organization: Faculty of Sci. and Tech., Keio Univ., Yokohama, Japan.
References: <199605091232.IAA01027@q.paradise.net>
Date: Fri, 10 May 1996 12:23:29 GMT
Lines: 57

In article <199605091232.IAA01027@q.paradise.net> emartin@schemers.COM (Edward C. Martin) writes:

    > In view of this equivalence, it would appear that the function F that gives 
    > the number for n >= 2 satisfies the recurrence relation

    >  F(n) = \sum_{i=1}^{n-1} [F(i) * F(n-i)]

    > based on the seed value F(1) = 1 (which has no practical meaning in terms 
    > of actual binary trees).
    >[...]

    > Sample values are

    >  F(4)  = 5
    >  F(5)  = 14
    >  F(10) = 4862
    >  F(20) = 1767263190

    > It grows faster than exponentially.

    > Is this a well-known problem? Does anyone know of a closed formula for 
    > F(n)?

This sequence is called Katalan(sp?) numbers.  This can also be
represented as F(n) = (2n - 2)! / ( n! (n - 1)! ).

And, here is a procedure that returns every instance of binary trees
for given sequence of leaves.

(define bit
  (lambda (leaves)
    (letrec ((g (lambda (left right)
		  (cons (list left '$ right)
			(and (pair? right)
			     (map (lambda (a) (cons a (cdr right)))
				  (g left (car right)))))))
	     (mapcon
	      (lambda (proc list)
		(if (null? list)
		    '()
		    (append (proc list) (mapcon proc (cdr list)))))))
      (cond ((null? leaves) nil)
	    ((null? (cdr leaves)) leaves)
	    (else (mapcon (lambda (trees)
			    (g (car leaves)
			       (car trees)))
			  (bit (cdr leaves))))))))

Example:
(bit '(a b c d))
=> ((a $ (b $ (c $ d))) ((a $ b) $ (c $ d))
    (a $ ((b $ c) $ d)) ((a $ (b $ c)) $ d) (((a $ b) $ c) $ d))

I learned these facts in my Lisp class.

Cheers,
				MAEDA Atusi
