Erlang中的二叉树最大路径

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

Binary Tree Maximum Path问题可以用DFS来解决,这里是一个可能的solution,用Python中的这种方法。

def maxPathSum(self, root):
    def maxSum(root):
        if not root:
            return 0
        l_sum = maxSum(root.left)
        r_sum = maxSum(root.right)
        l = max(0, l_sum)
        r = max(0, r_sum)
        res[0] = max(res[0], root.val + l + r)
        return root.val + max(l, r)
    
    res = [-float('inf')]
    maxSum(root)
    return res[0]

我尝试在Erlang中使用同样的方法。假设一个 node 看起来像这样:

{Value, Left, Right}

我想到了:

max_sum(undefined) -> 0;
max_sum({Value, Left, Right}) ->
    LeftSum = max(0, max_sum(Left)),
    RightSum = max(0, max_sum(Right)),
    %% Where to store the max? Should I use the process dictionary?
    %% Should I send a message?
    Value + max(LeftSum, RightSum).

max_path_sum(Root) ->
  %% Bonus question: how to represent -infinity in Erlang?
  max_sum(Root)

Erlang中没有全局变量,在DFS中如何跟踪最大值?我唯一想到的是使用进程字典或ETS表,或者可能有一个不同的进程可以保持最大值,但可能是我想多了,有一个更简单和惯用的方法?

klr1opcd

klr1opcd1#

最“蹩脚”的方法是将全局最大值作为第二个参数传递,并将其与局部最大值沿着返回:

max_sum(undefined, GlobalMax) -> {0, GlobalMax};
max_sum({Value, Left, Right}, GlobalMax0) ->
    {LeftSum, GlobalMax1} = max(0, max_sum(Left, GlobalMax0)),
    {RightSum, GlobalMax2} = max(0, max_sum(Right, GlobalMax1)),
    NewGlobalMax =
        case GlobalMax2 of
            undefined ->
                Value + LeftSum + RightSum
            _ ->
                max(GlobalMax2, Value + LeftSum + RightSum)
        end,
    {Value + max(LeftSum, RightSum), NewGlobalMax}.

max_path_sum(Root) ->
    {_, GlobalMax} = max_sum(Root, undefined),
    GlobalMax.

Erlang doesn't support infinity values in floats,所以我用原子undefined来表示最小值。

相关问题