0

I have a different request than what I saw on stackoverflow. Say my binary tree is of the form tree(Node, Leafs). There is no left or right leafs, only the attribute leafs.

How would you go about counting the node in that tree?

For example the tree could be:

tree(node1, [tree(node2)]), tree(node3, []), tree(node4, [tree(node6,[tree(node2,[])]).

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.