Here’s a small, pure Prolog module that will enumerate all finite binary trees (of increasing size), where
• a leaf is represented by the atom nil
• an internal node is t(Value, Left, Right) with Value an uninstantiated variable
Save this as, say, all_binary_trees.pl:
prolog
:- module(all_binary_trees, [binary_tree/1]).
/*
binary_tree(-T)
T is a binary tree (leaf = nil, node = t(Var,Left,Right))
with *uninstantiated* node‐values. Enumerates all shapes, in
order of increasing number of internal nodes.
*/
%----------------------------------------------------------------
% 1. Enumerate natural numbers: 0,1,2,3,...
% (fair: each N will eventually be reached)
%----------------------------------------------------------------
nat(0).
nat(N) :-
nat(M),
N is M + 1.
%----------------------------------------------------------------
% 2. Main predicate: pick a size N, then build a tree of size N
%----------------------------------------------------------------
binary_tree(T) :-
nat(N),
tree_of_size(N, T).
%----------------------------------------------------------------
% 3. tree_of_size(+N, -Tree)
% Tree has exactly N internal nodes.
% A node consumes 1, then splits the remaining into its children.
%----------------------------------------------------------------
tree_of_size(0, nil).
tree_of_size(N, t(Value, L, R)) :-
N > 0,
N1 is N - 1,
% split N1 into KL + KR = N1
between(0, N1, KL),
KR is N1 - KL,
tree_of_size(KL, L),
tree_of_size(KR, R).
Example session:
prolog
?- use_module(all_binary_trees).
true.
?- binary_tree(T).
T = nil ;
T = t(_A, nil, nil) ;
T = t(_A, t(_B, nil, nil), nil) ;
T = t(_A, nil, t(_B, nil, nil)) ;
T = t(_A, t(_B, nil, nil), t(_C, nil, nil)) ;
...
If you only want the first K trees in a list, you can do:
That’s all there is to it. This generator is “fair” in the sense that no shape is skipped—and you can keep backtracking indefinitely to see every finite‐shape binary tree.