如何使用Erlang计算恰好有一个子节点的节点?

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

当我试图找到只有一个孩子的节点时遇到了一些问题,但是函数没有返回正确的数字(继续返回0)
这是我的代码:

helper(Tree, Acc) ->
    case Tree of
    {Value, Left, Right} ->
     if
         {Value, Left, empty} -> helper(Left, Acc +1);
         {Value, empty, Right} -> helper(Right, Acc +1);
         {Value, Left, Right} -> helper(Left, Acc),
         helper(Right, Acc);
         true -> Acc
     end
    end.
jrcvhitl

jrcvhitl1#

您有两个问题:
1.代码中不需要if,您可以(也应该)直接在case语句上进行模式匹配。
1.在if/case的第三个子句中调用heper(Right, Acc)时,您没有保留调用helper(Left, Acc)的结果。
我没有测试它,但我认为如果您这样编写代码,您的代码应该可以工作:

helper(Tree, Acc) ->
    case Tree of
         {Value, Left, empty} -> helper(Left, Acc +1);
         {Value, empty, Right} -> helper(Right, Acc +1);
         {Value, Left, Right} -> helper(Right, helper(Left, Acc));
         _ -> Acc
    end.

事实上,您根本不需要case语句...

helper({Value, Left, empty}, Acc) -> helper(Left, Acc + 1);
helper({Value, empty, Right}, Acc) -> helper(Right, Acc + 1);
helper({Value, Left, Right}, Acc) -> helper(Right, helper(Left, Acc));
helper(_, Acc) -> Acc.

而且,如果你试图编译它,Erlang会立即告诉你Value在任何地方都是未使用的。

helper({_, Left, empty}, Acc) -> helper(Left, Acc + 1);
helper({_, empty, Right}, Acc) -> helper(Right, Acc + 1);
helper({_, Left, Right}, Acc) -> helper(Right, helper(Left, Acc));
helper(_, Acc) -> Acc.

但是,公平地说......我认为您仍然缺少{_, empty, empty}的一个子句。否则,您会将其视为具有恰好一个子节点的节点,而实际上它没有子节点......

helper({_, empty, empty}, Acc) -> Acc;
helper({_, Left, empty}, Acc) -> helper(Left, Acc + 1);
helper({_, empty, Right}, Acc) -> helper(Right, Acc + 1);
helper({_, Left, Right}, Acc) -> helper(Right, helper(Left, Acc));
helper(_, Acc) -> Acc.

相关问题