我正在尝试使用进程创建一个二叉树。
-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).
如果没有LeftNode
和RightNode
,我可以成功地创建树结构,但是我想在循环状态中保存LeftNode
和RightNode
。在创建节点时,我应该在函数参数中传递什么?
- 更新:感谢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);
1条答案
按热度按时间pengsaosao1#
试试这个。