An unordered binary tree is a tree where each node can have up to two children, but the order between the children is not important. Thus, each node in a non-empty unordered binary tree can be represented as a term of the form tree(Node,Children), where Children is an empty set (if Node is a leaf), or a set of one or two trees (if Node is an internal node). An empty unordered tree can be represented as nil. To simplify the implementation, we can represent sets as lists. For example, the unordered binary tree:
a
/ \
b c
/ \ |
d e f
can be represented as:
mytree(tree(a,
[tree(b,
[tree(d,[]),
tree(e,[])]),
tree(c,
[tree(f,[])])])).
To count the nodes in an unordered binary tree, we can use maplist/3 and sum_list/2 as following:
count_nodes(nil, 0).
count_nodes(tree(_Root, Children), N) :-
maplist(count_nodes, Children, Ns), % call count_nodes, recursively, for each child
sum_list([1|Ns], N). % add 1 to count the root
Here are some examples:
?- count_nodes(nil, N).
N = 0.
?- count_nodes(tree(a,[]), N).
N = 1.
?- count_nodes(tree(a,[tree(b,[])]), N).
N = 2.
?- count_nodes(tree(a,[tree(b,[]),tree(c,[])]), N).
N = 3.
?- mytree(T), count_nodes(T, N).
T = tree(a, [tree(b, [tree(d, []), tree(e, [])]), tree(c, [tree(f, [])])]),
N = 6.