functional-programmingtreeerlangbinary-treeerlang-supervisor

Is there a way to create a binary tree in Erlang using processes?


I am trying to create a binary tree using processes.

-module(binarytree).

-export([start/1, loop/2]).

start(N) ->
    P = spawn(?MODULE, loop, [N, self(), self(), self()]),
    P ! create_nodes,
    receive
    end.

loop(0, _, _, _) ->
    done;

loop(N, Root, LeftNode, RightNode) ->
    receive
        create_nodes ->
            MyPid = self(),
            LeftNode = spawn(?MODULE, loop, [N-1, MyPid, ???, ???]),
            RightNode = spawn(?MODULE, loop, [N-1, MyPid, ???, ???]),
            LeftNode ! create_nodes,
            RightNode ! create_nodes;
        _ ->
            ok
    end,
    loop(N, Root, LeftNode, RightNode).

Without LeftNode and RightNode I am creating tree structure successfully, but I want to save LeftNode and RightNode in loop's state. What should I pass in function arguments when creating nodes?

Update: Thanks to Nalin Ranjan. Change these lines:

MyPid = self(),
LeftNode = spawn(?MODULE, loop, [N-1, MyPid, ???, ???]),
RightNode = spawn(?MODULE, loop, [N-1, MyPid, ???, ???]),
LeftNode ! create_nodes,
RightNode ! create_nodes;

To:

MyPid = self(),
NewLeftNode = spawn(?MODULE, loop, [N-1, MyPid, "", ""]),
NewRightNode = spawn(?MODULE, loop, [N-1, MyPid, "", ""]),
NewLeftNode ! create_nodes,
NewRightNode ! create_nodes,
loop(N, Root, NewLeftNode, NewRightNode);

Solution

  • loop(N, Root, LeftNode, RightNode) -> 
     receive 
      create_nodes -> 
        MyPid = self(),
        NewLeftNode = spawn(?MODULE, loop, [N-1, MyPid, "empty-child-node", "empty-child-node"),
        NewRightNode = spawn(?MODULE, loop, [N-1, MyPid, "empty-child-node", "empty-child-node"]), 
        NewLeftNode ! create_nodes, 
        NewRightNode ! create_nodes, 
        loop(N, Root, NewLeftNode, NewRightNode); 
    
      _ -> ok 
    end, 
    loop(N, Root, LeftNode, RightNode). 
    
    

    Try this one out.