[Soluzione non testata]
Il modulo bt non fa parte della soluzionei dell'esercizio.
E' in aggiunta, per testarla.

-module(bt)
-export(leaf/1, node/3, getLabel/1, subtreeL/1, subtreeR/1, isLeaf/1)

leaf(X) -> [leaf,X].

node(X,T1,T2) -> [node,X,T1,T2].

getLabel([_,L|Rest]) -> L.

subtreeL([_,_,T1|_]) -> T1.

subtreeR([_,_,_,T2]) -> T2.

isLeaf([A|Rest]) -> A==leaf.





-module(apT)
-export(applytree/2, node/3) 

applytree(F,Tree) -> 
              Node = spawn(apT,node,[F,Tree,self()])
              receive
                  Result -> Result
              end.


node(F,Tree,PIDfather) -> 
                     LabRoot = bt:labelRoot(Tree),
                     if
                     bt:isLeaf(Tree) -> PIDfather!{self(),labRoot};
                     true ->                           
                            SubTL = bt:subTreeL(Tree),
                            SubTR = bt:subTreeR(Tree),   
                            NodeL = spawn(apT,node,[F,SubTL,self()]),
                            NodeR = spawn(apT,node,[F,SubTL,self()]),
                            receive
                                 {NodeL,ResultL} -> true,
                                 {NodeR,ResultR} -> true
                            end,
                            receive
                                 {NodeL,ResultL} -> true,
                                 {NodeR,ResultR} -> true
                            end,
                            ResultPIDfather!{self(),F(LabRoot,ResultL,ResultR)}
                     end.

