【问题标题】:Binary Tree Maximum Path in ErlangErlang中的二叉树最大路径
【发布时间】:2021-07-24 14:18:21
【问题描述】:

Binary Tree Maximum Path 问题可以通过使用 DFS 来解决。 这是在 Python 中使用这种方法的可能的solution

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 表,或者可能有一个可以保持最大值的不同流程,但也许我想多了,还有更简单和惯用的方法?

【问题讨论】:

    标签: erlang


    【解决方案1】:

    最“古怪”的方式是将全局最大值作为第二个参数传递,并将其与局部最大值一起返回:

    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 来表示一个最小值。

    【讨论】:

      猜你喜欢
      • 2018-08-10
      • 1970-01-01
      • 2020-11-29
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多