有没有办法在Erlang中使用进程创建二叉树?

6yoyoihd  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(149)

我正在尝试使用进程创建一个二叉树。

-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).

如果没有LeftNodeRightNode,我可以成功地创建树结构,但是我想在循环状态中保存LeftNodeRightNode。在创建节点时,我应该在函数参数中传递什么?

    • 更新:感谢Nalin Ranjan。**更改这些行:
MyPid = self(),
LeftNode = spawn(?MODULE, loop, [N-1, MyPid, ???, ???]),
RightNode = spawn(?MODULE, loop, [N-1, MyPid, ???, ???]),
LeftNode ! create_nodes,
RightNode ! create_nodes;

收件人:

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);
pengsaosao

pengsaosao1#

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).

试试这个。

相关问题