0

Can anyone help me how to realize predicate in Prolog which counts the all the node numbers of a binary tree?

For example:

tree1(tree(1,
        tree(2,
            tree(3,nil,nil),
            tree(4,nil,nil)),
        tree(5,
            tree(6,nil,nil),
            tree(7,nil,nil))
    )
). 

Would return 28. Anyone can help?

2
  • 2
    Are you sure about 23? Looks like 28 to me, or I am misunderstanding the question. Commented Mar 21, 2013 at 9:39
  • My mistake, it was 28 Commented Mar 21, 2013 at 14:32

1 Answer 1

1

The trivial recursive solution. Not tail-recursive.

treesum(nil, 0).
treesum(tree(X,T1,T2), S) :-
    treesum(T1, S1), treesum(T2, S2),
    S is X+S1+S2.
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the answer, helped me a lot. And how about multiplication? How could I realize that?
in this case I can't just change '+' to '*', because I did that and Prolog all the time gave me answer 0(The program GNU Prolog). Because when I traced this multiplication example, in each node it multiplyed also 0. Here is an example of multiplication, just first part, bu all the others are the same: 6 4 Exit: 0 is 3*(0*0) ? `
@John You are joking, right? Here is a riddle: When you add 0, nothing changes. What do you have to multiply to so that nothing changes?

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.