Add nodes of a tree. Prolog

1

Good morning, I am a beginner in Prolog and I am studying treatment of lists and trees. One question that I have is how can I add the nodes of a tree in binary principle. For example:

The trees are represented as a list as follows:

[[[[],1,[]],5,[[],4,[]]],7,[[],6,[]]]

Using a predicate like pej sumanodos (tree, S) must return the sum of nodes pej

?-sumanodos( [[[[],1,[]],5,[[],4,[]]],7,[[],6,[]]],S)
S=23

I can only use the following abstract type constructors and selectors:

nil([]).
leftnode([LN,_,_],LN)
root([_,RT,_],RT)
rightnode([_,_,RN],RN)
tree(RT,LN,RN,[LN,RT,RN])

I am particularly interested in the explanation, thank you very much in advance!

    
asked by Johann Molter 30.05.2017 в 11:56
source

2 answers

1

The sum of an empty tree is 0:

sumanodos([],0).

In the general case, the sum of the left branch and the sum of the right branch are recursively obtained, and the sum of the root is returned with both branches:

sumanodos([L,N,R],S) :-
    sumanodos(L,Sl),
    sumanodos(R,Sr),
    S is N+Sl+Sr.
    
answered by 30.05.2017 в 12:25
0

I do not work in Prolog but I will try to help you out. To go through the nodes of a tree you have to do it recursively. You have three ways to go through it, pre-order, in-order and post-order, if you only want to go through the tree without caring about the order in which you go through it, you can use any of the 3 methods. I leave you a website where you do the 3 tours, you only have to increase one variable each time you pass through a node. link

    
answered by 30.05.2017 в 12:09