【发布时间】: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